[英]How to split a string if the delimiter is one or more spaces?
I'm trying to get this to write every word from input in a new line, even if there are more spaces between words, but I can't figure out what is wrong with this. 我试图让它在新行中将输入中的每个单词都写在新行中,即使单词之间有更多空格,但是我无法弄清楚这有什么问题。
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);
I'm only getting the last letter from every word. 我只是从每个单词中得到最后一封信。 Any help, please?
有什么帮助吗?
And if let's say, I want to print out the nth word of phrase(n is from input), how can I do that? 如果说,我想打印出短语的第n个词(n来自输入),我该怎么做?
Since you are not using braces in your if
statement, this code gets executed in every iteration: 由于您不在
if
语句中使用花括号,因此此代码在每次迭代中都会执行:
currentWord = "";
So you reset the value of currentWord
. 因此,您可以重置
currentWord
的值。
You could simply use Split
method with StringSplitOptions.RemoveEmptyEntries
, no need to reinvent the wheel: 您可以将
Split
方法与StringSplitOptions.RemoveEmptyEntries
,而无需重新发明轮子:
var words = phrase.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Thats what happens when you don't use curly braces in if
and while
bodies... 那就是当您在
if
和while
主体中不使用花括号时会发生什么...
Write them both with braces and spot the difference with your current code. 用大括号写它们,并在当前代码中找出区别。
I would probably do it this way.. 我可能会这样。
First add this reference: 首先添加此参考:
using System.Text.RegularExpressions;
Then you can use a simple regex to split your string into words and a foreach loop to display the words: 然后,您可以使用简单的正则表达式将字符串拆分为单词,并使用foreach循环显示单词:
var phrase = Console.ReadLine();
var words = Regex.Split(phrase, @"\s+");
foreach(var word in words)
Console.WriteLine(word)
This is also a lot cleaner compared to the code you have, which makes it a lot easier to read, understand and maintain. 与您拥有的代码相比,这也更简洁,这使得阅读,理解和维护变得更加容易。
You can replace char with Replace
method 您可以使用
Replace
方法替换char
Follow code: 遵循代码:
Console.ReadLine().Replace(" ","");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.