在 C# 中至少包含六个单词的字符串的 while 循环



我正在尝试编写一个while循环验证,以验证用户在输入具有以下条件的句子时的响应:

  • 字符串为空或空
  • 句子必须至少为六个字。

我能够使空或空条件按预期工作,但"必须至少六个字"目前没有按预期工作。每当我输入少于六个单词的句子时,它就可以接受它。但是,如果我输入一个包含六个或更多单词的句子,它会在不应该输入时提示已建立的错误消息。

while (String.IsNullOrEmpty(sentence) || sentence.Length != 6)
{
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
sentence = ReadLine();
}
else
{
Console.WriteLine("rnThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
sentence = ReadLine();
}
}

我到底做错了什么?

string sentence = Console.ReadLine();
while (true)
{
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
}
else if (sentence.Split(' ').Length < 6)
{
Console.WriteLine("rnThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
}
else break;
sentence = Console.ReadLine();
}

while (String.IsNullOrEmpty(sentence) || sentence.Length != 6)更改为

while (String.IsNullOrEmpty(sentence) || sentence.Split(' ').Length < 6)

sentence.Length返回字符串中的字符数。您必须将句子拆分为单词。

string[] words = sentence.Split();

在空格字符处拆分。

因此,您可以将循环编写为

while (String.IsNullOrEmpty(sentence) || sentence.Split().Length < 6)
{
...
}

这里Length是由拆分产生的字符串数组的长度。

注意,如果句子null,C# 布尔表达式的短路计算将不会执行||后面的子表达式。因此,您不会得到空引用异常。

首先,您可以在像波纹管这样的条件下改变你... 它会给你一个长度小于六的句子 而(句子。长度 <6( 当您想获得一个长度为六个单词的单词时,请尝试以下条件...

sentence.Split(' ').Length >= 6

//首先尝试更改,而条件如波纹管....然后试试下面的代码。

public static void Main(string[] args)
{
int count = 0;
inputSteream:
Console.WriteLine("Enter your  sentence: ");
string sentence = Console.ReadLine();
while (!String.IsNullOrEmpty(sentence) && sentence.Length >= 6)
{
foreach (var item in sentence.Split(' '))
{
if (item.Length >= 6)
{
Console.WriteLine("The sentece is {0}", item);
count++;
break;
}
}
break;
}
if (count == 0)
{
goto inputSteream;
}
Console.ReadKey();
}

尝试以下示例代码

string sentence=Console.ReadLine();
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
sentence = Console.ReadLine();
}
else if(sentence.Length!=6)
{
Console.WriteLine("rnThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
sentence =  Console.ReadLine();
}
else
{
Console.WriteLine("Your entered string length is'{0}' and word is{1}", sentence.Length,sentence);
}

最新更新