循环会在整个单词范围内重复输出。
我尝试在循环的内部和外部启动console.write。我还尝试更改了增量子和子字符串的值。
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i <= wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
//theLetter = theLetter.ToLower();
string rebuilt = new string(wordArray);
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
Console.ReadLine();
console.write应该只显示一次输出。
答案 0 :(得分:1)
您需要将Console.WriteLine移动到循环之外。另外,您需要更改循环条件以避免ArguementOutOfRangeException。
sudo apt update
您的代码中还有一个错误。您正在将userWord转换为小写,但没有存储结果。
for (int i = 0; i < wordArray.Length; i++)
以上行需要替换为
userWord.ToLower();
完整代码
userWord = userWord.ToLower();
仅供参考,您也可以使用Regex实现相同的目的。
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord = userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i < wordArray.Length; i++)
{
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
}
var rebuildWord = new string(wordArray);
Console.WriteLine("Your word is now: {0}", rebuildWord);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
答案 1 :(得分:1)
这很简单。您应该在打印之前检查循环是否在最终迭代中。
Console.WriteLine("Enter a word.");
string userWord = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("You wrote {0}", userWord);
Console.WriteLine();
userWord.ToLower();
char[] wordArray = userWord.ToArray();
for (int i = 0; i <= wordArray.Length; i++)
{
string theLetter = userWord.Substring(i, 1);
//theLetter = theLetter.ToLower();
string rebuilt = new string(wordArray);
if (wordArray[i] == 'a' || wordArray[i] == 'e' || wordArray[i] == 'i' || wordArray[i] == 'o' || wordArray[i] == 'u')
{
wordArray[i] = '$';
}
if(i==userWord.Length)
{
Console.WriteLine("Your word is now: {0}", rebuilt);
Console.WriteLine("The total number of letters in your word is {0}", userWord.Length);
}
}
Console.ReadLine();