[英]Split a string C#
我需要一点帮助。 我有一个字符串
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 托马斯
您可以使用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)
};
只因为我无聊
此函数返回三个电话号码的字典。
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.