[英]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.