首页 > 解决方案 > 将字符串拆分为子字符串,节省大空间

问题描述

我有一个string这样的填充物 -

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

我需要将其拆分substrings,但中间的空格也必须写入字符串数组。

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

    ...
}    

我预计 :

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

标签: c#stringsplit

解决方案


您可以尝试正则表达式匹配所需的块:

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
}

演示:

  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);

结果:

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

推荐阅读