向数组添加字符串

时间:2019-01-08 18:35:22

标签: c#

我只是用C#做一个小项目(我是一个初学者),我的代码基本上是在问你“这句话有多少个单词?”然后要求您输入每个单词,一旦获得所有单词,它就会在每个单词后面附加“ ba”以打印出来。

我知道我是一个真正的初学者,我的代码可能只是在开玩笑,但是您能帮我解决这个问题吗?

Console.WriteLine("How many words are in this sentence?");

int WordAmount = Convert.ToInt32(Console.ReadLine());
int i = 1;

while (i <= WordAmount)
{
    Console.WriteLine("Enter a word");
    string[] word = new string[] { Console.ReadLine() };
    i++;
}

Console.WriteLine(word + "ba");

3 个答案:

答案 0 :(得分:1)

您接近,您只有一个问题。

string[] word = new string[] { Console.ReadLine() };

您正在while循环范围内创建一个新的数组列表。这不仅会在每个循环中消失,这意味着您永远不会保存旧词,而且您也将无法在循环之外使用它,从而使它无用。

创建一个string[] words = new string[WordAmount];。然后遍历它,将您的Console.ReadLine()添加到其中,最后,遍历一下,再Console.WriteLine(words[i] + "ba");

答案 1 :(得分:0)

string[] wordList = new string[WordAmount];
while (i <= WordAmount)
{
    Console.WriteLine("Enter a word");
    wordList[i-1] = Console.ReadLine() ;
    i++;
}

foreach (var item in wordList)
    Console.WriteLine(item + "ba");

工作小提琴:https://dotnetfiddle.net/7UJKwN

您的代码有多个问题。首先,您需要在while循环之外定义数组,然后一个一个地填充它。

为了读/写字符串数组(string []),您需要遍历(迭代)它。

我的代码实际上迭代了您的wordList。在第一个While循环中,我要迭代以填充wordList数组。然后在第二个循环中打印

答案 2 :(得分:0)

首先,考虑将单词存储在某种类型的集合中,例如列表。

List<string> words = new List<string>();
while (i <= WordAmount)
{
    Console.WriteLine("Enter a word");
    string word = Console.ReadLine();
    words.Add(word);
    i++;
}

我不认为您的代码可以编译-原因是您试图在定义它的范围之外使用word变量。在我的解决方案中,我声明并初始化了一个字符串列表(因此,在这种情况下,如果用户需要输入单词,则可以在内部范围(用户输入单词的大括号之间的区域)中访问它。

要打印所有单词,您必须遍历列表并添加一个“ ba”部分。像这样:

foreach(var word in words)
{
    Console.WriteLine(word + "ba");
}

或更简洁地说:

words.ForEach(o => Console.WriteLine(o + "ba"));

如果要在不使用换行符的情况下打印句子,则可以使用LINQ:

var wordsWithBa = words.Select(o => o + "ba ").Aggregate((a, b) => a + b);
Console.WriteLine(wordsWithBa);

尽管我建议您在对C#更加熟悉之后再学习LINQ:)

您可以查看herehere来熟悉变量的集合和范围的概念。

您还可以使用StringBuilder类来完成此任务(如果涉及到内存,我的LINQ方法不是很有效,但是我认为它足以满足您的目的)。

相关问题