2010-03-11 83 views
7

我有9個字母的字符串。c#字符串操作

string myString = "123987898"; 

我要檢索的前3個字母「123」 然後2個以上的字母「98」 ,然後加入4-多個字母「7898」。

其中c#字符串函數支持此功能。

+0

好像功課? – Kerido 2010-03-11 18:53:09

+0

@Kerido - 可能需要分離社會安全號碼的部分,這並不一定意味着作業:) – 2010-03-11 18:55:31

+0

仍然聽起來像功課。不過不是壞事。就這樣標籤。 – 2010-03-11 19:21:26

回答

19

您可以使用Substring

myString.Substring(0,3) 
myString.Substring(3,2) 
myString.Substring(5,4) 

也有可能使其超過必要的複雜使用正則表達式和LINQ的組合:

string myString = "123987898"; 
Regex regex = new Regex("(.{3})(.{2})(.{4})"); 
string[] bits = regex 
    .Match(myString) 
    .Groups 
    .Cast<Group>() 
    .Skip(1) 
    .Select(match => match.Value) 
    .ToArray(); 
+0

第一部分爲+1。我喜歡保持簡單。第二部分是概念的完整證明,但如果我在生產代碼中看到它,我會重構它。 – 2010-03-11 19:26:49

0

處理的最好的和可靠的方法這是使用正則表達式

 
public Regex MyRegex = new Regex(
     "(?\\d{3})(?\\d{2})(?\\d{4})", 
    RegexOptions.IgnoreCase 
    | RegexOptions.CultureInvariant 
    | RegexOptions.IgnorePatternWhitespace 
    | RegexOptions.Compiled 
    ); 

然後你可以CCESS他們通過Match實例

 
Match m = MyRegex.Match("123987898"); 
if (m.Success){ 
    int first3 = int.Parse(m.Groups["first3"].Value; 
    int next2 = int.Parse(m.Groups["next2"].Value; 
    int last4 = int.Parse(m.Groups["last4"].Value; 

    /* Do whatever you have to do with first3, next2 and last 4! */ 
} 
1

沒有什麼內置的Groups屬性,但它是很容易使自己。

public static IEnumerable<string> SplitBySize(string value, IEnumerable<int> sizes) 
{ 
    if (value == null) throw new ArgumentNullException("value"); 
    if (sizes == null) throw new ArgumentNullException("sizes"); 

    var length = value.Length; 
    var currentIndex = 0; 
    foreach (var size in sizes) 
    { 
     var nextIndex = currentIndex + size; 
     if (nextIndex > length) 
     { 
      throw new ArgumentException("The sum of the sizes specified is larger than the length of the value specified.", "sizes"); 
     } 
     yield return value.Substring(currentIndex, size); 
     currentIndex = nextIndex; 
    } 
} 

示例用法

foreach (var item in SplitBySize("1234567890", new[] { 2, 3, 5 })) 
{ 
    Console.WriteLine(item); 
} 
Console.ReadKey();