为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕姐8265434 2022-01-09 16:00:11
我正在尝试编写一个while循环验证来验证用户在输入具有以下条件的句子时的响应:字符串为空或空句子必须至少六个字。我能够让 null 或 empty 条件按预期工作,但“必须至少是六个字”目前没有按预期工作。每当我输入一个少于六个单词的句子时,它都会接受它。但是,如果我输入一个包含六个或更多单词的句子,它会在不应该时提示已建立的错误消息。        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("\r\nThe sentece entered isn't valid. Must have a least six words!");                Console.WriteLine("Enter a sentence with a least 6 words: ");                sentence = ReadLine();            }        }我到底做错了什么?
查看完整描述

3 回答

?
DIEA

TA贡献1820条经验 获得超3个赞

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("\r\nThe 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();

        }


查看完整回答
反对 回复 2022-01-09
?
倚天杖

TA贡献1828条经验 获得超3个赞

sentence.Length返回字符串中的字符数。你必须把句子分成单词。


string[] words = sentence.Split();

在空白字符处拆分。


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


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

{

    ...

}

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


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


查看完整回答
反对 回复 2022-01-09
?
慕运维8079593

TA贡献1876条经验 获得超5个赞

// 首先尝试改变 while 条件,如波纹管 ....然后尝试波纹管代码..


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();

    }


查看完整回答
反对 回复 2022-01-09
  • 3 回答
  • 0 关注
  • 231 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号