Eva
Eva

Reputation: 37

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?

Upvotes: 0

Views: 45

Answers (4)

Reza Jenabi
Reza Jenabi

Reputation: 4279

You can replace char with Replace method

Follow code:

Console.ReadLine().Replace(" ","");

Upvotes: 0

Saeed Prez
Saeed Prez

Reputation: 778

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:

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.

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Since you are not using braces in your if statement, this code gets executed in every iteration:

currentWord = "";

So you reset the value of currentWord.

You could simply use Split method with StringSplitOptions.RemoveEmptyEntries, no need to reinvent the wheel:

var words = phrase.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 2

InBetween
InBetween

Reputation: 32750

Thats what happens when you don’t use curly braces in if and while bodies...

Write them both with braces and spot the difference with your current code.

Upvotes: 1

Related Questions