【问题标题】:Split a string C#拆分字符串 C#
【发布时间】:2017-06-16 21:22:48
【问题描述】:

我需要一点帮助。 我有一个字符串

string source = "Mobile: +49 (123) 45678Telephone: +49 (234) 567890Fax: +49 (345) 34234234";

我想分开:

Mobile: +49 (123) 45678
Telephone: +49 (234) 567890
Fax: +49 (345) 34234234

感谢您的支持 BR托马斯

【问题讨论】:

  • 欢迎来到 StackOverflow!你都尝试了些什么?你在哪里失败了?
  • 然后呢?为什么你不能?你尝试过什么吗?查找TelephoneFax 的索引很容易,即使它不是最快的解决方案
  • 嗨,Thomas... 通常会尝试第一个解决方案,并附上结果以及您当前的问题是什么。谢谢
  • 搜索正则表达式。这就是你的解决方案。

标签: c# string split


【解决方案1】:

你可以使用Regex.Matches():

string source = "Mobile: +49 (123) 45678Telephone: +49 (234) 567890Fax: +49 (345) 34234234";

string[] phones = Regex
                 .Matches(source, "[A-Za-z]+: \\+([0-9)( ])+")
                 .Cast<Match>()
                 .Select(i => i.ToString())
                 .ToArray();

你可以使用IndexOf():

string source = "Mobile: +49 (123) 45678Telephone: +49 (234) 567890Fax: +49 (345) 34234234";

var telephoneIndex = source.IndexOf("Telephone", StringComparison.InvariantCulture);
var faxIndex = source.IndexOf("Fax", StringComparison.InvariantCulture);

string[] phones =
{
    source.Substring(0, telephoneIndex - 1),
    source.Substring(telephoneIndex, faxIndex - 1),
    source.Substring(faxIndex, source.Length - faxIndex)
};

【讨论】:

  • 哇——响应速度非常快。感谢罗马 - 两种解决方案都有效。非常非常感谢。
【解决方案2】:

只是因为我很无聊

此函数返回三个电话号码的字典。

Dictionary<String, String> ParseTelephones(string source)
{
    var tags = new[] {"Telephone:","Fax:","Mobile:"};
    var dict = new Dictionary<String, String>();

    tags.Any(a => { source = source.Replace(a, "|" + a); return true; });

    source.Split("|")
          .Skip(1)
          .Select(a => a.Split(":").Trim())
          .Any(a => { dict.Add(a[0], a[1]); return true;})
          .ToList();

    return dict;
}

【讨论】:

  • 感谢您的宝贵时间 ;-) 我已经知道有很多解决方案
猜你喜欢
  • 2011-02-13
  • 2011-11-25
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多