I am working on an requirement where I need to get all the words from a string into an array. A 'word' is described as any sequence of non-space charachters. There can be any number of whitespace charachters present in the string.
Input Examples :
" Hello World!! "
"Hello World!!"
" Hello World!! "
In all above cases the output should be ["Hello","World!!"]
Now I have tried to solve the example myself and have below code :
public string[] GetWords(string s)
{
s=s.Trim();
while(s.Contains(" "))
{
s = s.Replace(" ", " ");
}
string[] input=s.Split(' ');
return input;
}
I am getting correct result using the above code. My concerns is there any way the code can be made clean or more optimized than it currently is.
string.Split(' ', StringSplitOptions.RemoveEmptyEntries)would be an idea