亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超2個贊

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 關注
  • 180 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號