[英]How to split a string if the delimiter is one or more spaces?
我試圖讓它在新行中將輸入中的每個單詞都寫在新行中,即使單詞之間有更多空格,但是我無法弄清楚這有什么問題。
string phrase = Console.ReadLine();
string currentWord = "";
for (int i = 0; i < phrase.Length; i++)
{
if (phrase[i] == ' ')
Console.WriteLine(currentWord);
currentWord = "";
while (phrase[i] == ' ')
i++;
if (phrase[i] != ' ')
currentWord += phrase[i];
}
Console.WriteLine(currentWord);
我只是從每個單詞中得到最后一封信。 有什么幫助嗎?
如果說,我想打印出短語的第n個詞(n來自輸入),我該怎么做?
由於您不在if
語句中使用花括號,因此此代碼在每次迭代中都會執行:
currentWord = "";
因此,您可以重置currentWord
的值。
您可以將Split
方法與StringSplitOptions.RemoveEmptyEntries
,而無需重新發明輪子:
var words = phrase.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
那就是當您在if
和while
主體中不使用花括號時會發生什么...
用大括號寫它們,並在當前代碼中找出區別。
我可能會這樣。
首先添加此參考:
using System.Text.RegularExpressions;
然后,您可以使用簡單的正則表達式將字符串拆分為單詞,並使用foreach循環顯示單詞:
var phrase = Console.ReadLine();
var words = Regex.Split(phrase, @"\s+");
foreach(var word in words)
Console.WriteLine(word)
與您擁有的代碼相比,這也更簡潔,這使得閱讀,理解和維護變得更加容易。
您可以使用Replace
方法替換char
遵循代碼:
Console.ReadLine().Replace(" ","");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.