【问题标题】:Split the string into substrings with saving big spaces将字符串拆分为子字符串,节省大空间
【发布时间】:2019-08-05 09:05:54
【问题描述】:

我有一个string 填写了这样的内容 -

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

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

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] = ".---";
...

【问题讨论】:

  • 您可能有固定宽度的数据并且必须在列索引上拆分而不是在空格上拆分,或者您有制表符分隔的数据并且必须在制表符上而不是空格上拆分。
  • @OwenPauling 看起来不像是真正的复制品。此处的 OP 不想保留所有分隔符。只有一个具有两种含义的:作为分隔符和作为符号

标签: c# string split


【解决方案1】:

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

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] = "."

【讨论】:

  • 感谢您的帮助!我有一个错误:当前上下文中不存在名称“匹配”。我怎么理解,我需要初始化它,我应该如何正确地做呢?
  • @Roomey:很抱歉打错了;它应该是 lambda .Select(match =&gt; match.Value...(请看我的编辑)
【解决方案2】:

下面也试试。它与正则表达式本身有关。

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

输出如下

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

我只是将所有连续的空格 (>=2) 替换为一个空格,而不是 split 字符串。希望这会有所帮助。

【讨论】:

  • 你的想法有点笼统:code = Regex.Replace(code, @"\s{2,}", m =&gt; new string(' ', m.Value.Length == 2 ? 1 : 2));(如果我们有 2 个空格,我们将它们视为 1,如果 2+ 个空格 - 视为 2)
猜你喜欢
  • 2011-11-25
  • 1970-01-01
  • 2015-12-28
  • 2019-05-22
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
相关资源
最近更新 更多