【问题标题】:Use a char to display a word使用 char 显示单词
【发布时间】:2023-03-14 14:47:01
【问题描述】:

C# 中的新功能,我必须为以下内容编写一个控制台应用程序。

用户可以输入他的单词,单词被存储到一个数组中,

提示用户输入一个字符,该字符将检索所有具有该字符的单词。我不知道如何在 if 语句中设置条件以及如何使用用户输入来检索单词。这是我的尝试代码:

int WCount;
string LargestWord = " ";
string SmallestWord = " ";
int vowelcount = 0;

List<string> wordsarr = new List<string>();
Console.WriteLine("How many words are you going to enter?");
WCount = int.Parse(Console.ReadLine());

for (int j = 0; j < WCount; j++)
{
  Console.WriteLine("Please enter your word");
  wordsarr.Add(Console.ReadLine());
  LargestWord = wordsarr[0];
  SmallestWord = wordsarr[1];
  string vowel = wordsarr[j].ToString();

  if(LargestWord.Length<wordsarr[j].Length)
  {
     LargestWord = wordsarr[j];
  }
  else if (SmallestWord.Length>wordsarr[j].Length)
  {
     SmallestWord = wordsarr[j];
                        }
     Console.WriteLine("Please enter a letter: ");
     char userinput = char.Parse(Console.ReadLine());

     if (userinput == wordsarr[j])
     {

     }
   }

【问题讨论】:

  • 您肯定不想要求用户在每次迭代时输入一个字母。你不想在开始循环之前问这个吗?
  • 是的,乔恩,我还在学习,谢谢

标签: c# string char


【解决方案1】:

我会这样做:

Console.WriteLine("How many words are you going to enter?");
int wordCount = int.Parse(Console.ReadLine());

string[] words = new string[wordCount];
for (int i = 0; i < words.Length; i++)
{
  Console.WriteLine("Please enter your word");
  words[i] = Console.ReadLine();
}

Console.WriteLine("Please enter a letter: ");
string searchChar = Console.ReadLine();

for (int i = 0; i < words.Length; i++)
{
  string word = words[i];
  if (word.Contains(searchChar) == true)
  {
     Console.WriteLine(word);
  }
}

【讨论】:

  • 如果您觉得通过添加== true 可以更好地阅读条件表达式,则应将其作为局部变量取出,并为其命名以表明其含义。不过,在这种情况下,word.Contains(searchChar) 在没有 == true 的情况下会读得很好。
【解决方案2】:

您可以使用在 wordsarr 上调用的方法 find ,例如 wordsarr.Find() 请在此处查看如何使用查找方法http://www.codeproject.com/Articles/388257/Csharp-Tips-Using-delegate-in-List-Find-predicate 要检查字符串是否包含给定字符,请看这里How can I check if a string contains a character in C#?

【讨论】:

  • 我不能使用任何功能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-12
  • 2015-11-13
  • 2010-12-28
相关资源
最近更新 更多