【问题标题】:C# How split a string containing numbers in array [closed]C#如何拆分数组中包含数字的字符串[关闭]
【发布时间】:2014-06-19 00:37:35
【问题描述】:

嗨,我有一个这样的字符串:

string test = "1Hello World  2I'm a newbie 33The sun is big 176The cat is black";

我想拆分字符串并放入这样的数组中:

1 Hello World
2 I'm a newbie 
33 The sun is big 
176 The cat is black

结果可能在 String[]、ArrayList、List 或 Linq 中

添加了我尝试过但不起作用的内容..

 ArrayList oArrayList = new ArrayList();
 Regex oRegex = new Regex(@"\d+");
 Match oMatch = oRegex.Match(test);
 int last = 0;

 while (oRegex.Match(test).Success)
 {
     oArrayList.Add(oMatch.Value + " " + test.Substring(last, oMatch.Index));
     last = oMatch.Index;
     test = test.Remove(0, oMatch.Index);
     oMatch = oRegex.Match(test);
 }

【问题讨论】:

  • 我希望你喜欢正则表达式,因为我有一种感觉很快就会出现......
  • "结果可能在 String[]、ArrayList、List 或 Linq 中"听起来像是一道家庭作业题
  • 可能不是作业,也可能是“如何解析node.InnerXml的结果(ToString()的其他一些明确定义的格式/对象树)的XY问题
  • 到目前为止你尝试过什么?正则表达式将是一种方法,或者更冗长的方法是遍历 char 数组并尝试将字符解析为双精度......很多方法来完成这项作业......
  • 其实不是功课,是一个项目,我试图从一个旧的 yk2 项目中解析一个巨大的文件,我开始做更小的测试,但我的头在这个时候已经精疲力竭了 :(

标签: c# arrays string split


【解决方案1】:

试试这个:

string test = "1Hello World  2I'm a newbie 33The sun is big 176The cat is black";

Regex regexObj = new Regex(@"(\d+)([^0-9]+)", RegexOptions.IgnoreCase);
Match match = regexObj.Match(test);
while (match.Success) 
{
  string numPart = match.Group[1].Value;
  string strPart = match.Group[2].Value;
  match = match.NextMatch();
}

输出:

【讨论】:

  • 我试过这个解决方案,它奏效了!
【解决方案2】:

说实话很简单

 string test = "1Hello World  2I'm a newbie 33The sun is big 176The cat is black";
 var tmp = Regex.Split(test,@"\s(?=\d)");

tmp 将是一个字符串数组

【讨论】:

  • 不错的选项,但结果中小数点和后面的文本之间没有空格
  • 它捕获小数点前的空格。您甚至尝试在示例控制台应用程序中运行它吗?如果你想要空格或者小数点前没有空格,你可以稍微修改一下正则表达式来得到你想要的,但这是最简单的方法。
【解决方案3】:

给定输入字符串test,您可以使用Regex.Split 在小数边界上拆分字符串。在每个元素的数字和文本之间添加空格需要在每个元素上调用 Regex.Match 以获得所需的格式:

var r = Regex.Split(test, @"(?<=\D)(?=\d)") // split at each boundary 
                                            // between a non-digit (\D)
                                            // and digit (\d).
            .Select(a=>Regex.Match(a, @"(\d+)(.*)").Result("$1 $2"));
                                           // ^ insert a space between
                                           // decimal and following text

结果是IEnumerable&lt;string&gt;,可以在 Linq 中根据需要进行处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多