Roomey
Roomey

Reputation: 716

Split the string into substrings with saving big spaces

I have a string filled something like this -

".... . -.--   .--- ..- -.. ."

I need to split it to substrings, but a space in the middle must be written to string array too.

public static string Decode(string morseCode)
{  
    string[] words = morseCode.Split(new char[] { ' ' });

    ...
}    

I expect :

words[0] = "...."; 
words[1] = "."; 
words[2] = "-.--"; 
words[3] = " ";     // <- Space in the middle should be preserved
words[4] = ".---";
...

Upvotes: 3

Views: 139

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

You can try regular expressions in order to match required chunks:

using System.Linq;
using System.Text.RegularExpressions;

public static string Decode(string morseCode) {
  string[] words = Regex.Matches(morseCode, @"(?<=^|\s).+?(?=$|\s)")
    .Cast<Match>()
    .Select(match => match.Value.All(c => char.IsWhiteSpace(c)) 
       ? match.Value 
       : match.Value.Trim())
    .ToArray();

  //Relevant code here
}

Demo:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string morseCode = ".... . -.--   .--- ..- -.. .";

  string[] words = Regex.Matches(morseCode, @"(?<=^|\s).+?(?=$|\s)")
    .Cast<Match>()
    .Select(match => match.Value.All(c => char.IsWhiteSpace(c)) 
       ? match.Value 
       : match.Value.Trim())
    .ToArray();

  string report = string.Join(Environment.NewLine, words
    .Select((word, i) => $"words[{i}] = \"{word}\""));

  Console.Write(report);

Outcome:

words[0] = "...."
words[1] = "."
words[2] = "-.--"
words[3] = " "
words[4] = ".---"
words[5] = "..-"
words[6] = "-.."
words[7] = "."

Upvotes: 3

DhavalR
DhavalR

Reputation: 1417

Try below also. It is with Regex itself.

string code = ".... . -.--   .--- ..- -.. .";
    code = Regex.Replace(code, @"(\s{2})", " ").ToString();
    string[] codes = code.Split(' ');
    for (int i=0; i<codes.Length;i++){
    Console.WriteLine(i + " - "+codes[i]);
    }

The output is as below

0 - ....
1 - .
2 - -.--
3 - 
4 - .---
5 - ..-
6 - -..
7 - .

I just replaced all consecutive spaces (>=2) with one space and than split the string. Hope this will help.

Upvotes: 0

Related Questions