简体   繁体   English

拆分字符串 C#

[英]Split a string C#

I need a little bit help.我需要一点帮助。 I have a string我有一个字符串

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

And I want to split in this:我想分成:

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

Thanks for your support BR Thomas感谢您的支持 BR 托马斯

You can use Regex.Matches() :您可以使用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();

OR或者

You can use IndexOf() :您可以使用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)
};

Only because I'm bored只因为我无聊

This function returns a dictionary of the three phone numbers.此函数返回三个电话号码的字典。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM