2010-08-27 58 views
2

我看到這個question,要求給一個字符串「史密斯;羅傑斯;麥卡倫」你怎麼能產生一個集合。答案是使用String.Split。有什麼替代拆分字符串在C#中,不使用String.Split()

如果我們沒有內置Split(),你會做什麼?

更新:

我承認寫一個分割功能是相當容易的。以下是我會寫的。使用IndexOf遍歷字符串並使用Substring提取。

string s = "smith;rodgers;McCalne"; 

string seperator = ";"; 
int currentPosition = 0; 
int lastPosition = 0; 

List<string> values = new List<string>(); 

do 
{ 
    currentPosition = s.IndexOf(seperator, currentPosition + 1); 
    if (currentPosition == -1) 
     currentPosition = s.Length; 

    values.Add(s.Substring(lastPosition, currentPosition - lastPosition)); 

    lastPosition = currentPosition+1; 

} while (currentPosition < s.Length); 

我把在SSCLI實施偷看其類似於上面除了它處理方法更多使用案例,它使用一種不安全的方法去子提取之前確定分離器的索引。

其他人建議如下。

  1. 擴展,使用迭代器塊
  2. 正則表達式的建議方法(未實施)
  3. LINQ的聚合方法

是這個嗎?

+4

我不明白的問題;是不是答案「寫一個拆分方法」?這並不是一個困難的寫作方法。 – 2010-08-27 22:50:14

+5

讓我們沒有IndexOf()。獎金根本不使用System.String。 – 2010-08-28 00:41:21

回答

9

編寫您自己的Split等價物是相當簡單的。

下面是一個簡單的例子,但實際上您可能想創建一些重載以獲得更大的靈活性。 (好吧,在現實你只是使用框架的內置Split方法!)

string foo = "smith;rodgers;McCalne"; 
foreach (string bar in foo.Split2(";")) 
{ 
    Console.WriteLine(bar); 
} 

// ... 

public static class StringExtensions 
{ 
    public static IEnumerable<string> Split2(this string source, string delim) 
    { 
     // argument null checking etc omitted for brevity 

     int oldIndex = 0, newIndex; 
     while ((newIndex = source.IndexOf(delim, oldIndex)) != -1) 
     { 
      yield return source.Substring(oldIndex, newIndex - oldIndex); 
      oldIndex = newIndex + delim.Length; 
     } 
     yield return source.Substring(oldIndex); 
    } 
} 
1

正則表達式?

或者只是子串。這是Split在內部的作用

+0

哈哈,我認爲OP的本質是要問如何實施拆分方法。 – 2010-08-27 23:11:05

2

你讓你自己的循環來分割。這是一個使用Aggregate擴展方法。效率不是很高,因爲它使用的字符串+=運營商,所以應該沒有真正被使用,只能作爲一個例子,但它的工作原理:

string names = "smith;rodgers;McCalne"; 

List<string> split = names.Aggregate(new string[] { string.Empty }.ToList(), (s, c) => { 
    if (c == ';') s.Add(string.Empty); else s[s.Count - 1] += c; 
    return s; 
}); 
相關問題