0

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.

5
  • The definition of "clean" might be opinion-based. For "optimized", you also need to specify in which way: fast? small memory footprint? small code size? Commented Jul 15, 2020 at 14:08
  • 4
    string.Split(' ', StringSplitOptions.RemoveEmptyEntries) would be an idea Commented Jul 15, 2020 at 14:09
  • @dymanoid I was looking for result in less number of steps than I am performing. Commented Jul 15, 2020 at 14:11
  • @Homungus Thanks, your solution did the trick for me Commented Jul 15, 2020 at 14:12
  • Also without RegEx, to adapt: stackoverflow.com/questions/58734248/… Commented Jul 15, 2020 at 16:37

2 Answers 2

2

Use the following code snippet:

var str = "  Hello World!!  ";
string[] array = str.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
 

The result will be ["Hello","World!!"]

Note: new Char[] { ' ' } if multiple characters need to be handled. Otherwise, you can use the following

string[] array = str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

Comments

2

I would use a regular expression:

using System.Text.RegularExpressions;

...

public string[] GetWords(string s) =>
    Regex.Matches(s, @"[^\s]+")
        .Cast<Match>()
        .Select(x => x.Value)
        .ToArray();

1 Comment

I would use Regex.Split().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.