2009-07-14 131 views

回答

257

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

例子:

string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]"; 
string[] stringSeparators = new string[] {"[stop]"}; 
string[] result; 

// ... 
result = source.Split(stringSeparators, StringSplitOptions.None); 

foreach (string s in result) 
{ 
    Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s); 
} 
51

可以使用Regex.Split方法,像這樣:

Regex regex = new Regex(@"\bis\b"); 
string[] substrings = regex.Split("This is a sentence"); 

foreach (string match in substrings) 
{ 
    Console.WriteLine("'{0}'", match); 
} 

編輯:這滿足你給的例子。注意,普通的String.Split也將在單詞的末尾拆分的「」「這個」,因此爲什麼我用正則表達式方法,其中包括圍繞「」字邊界。但是,請注意,如果您錯誤地編寫了此示例,則String.Split可能就足夠了。從文檔

+0

@編輯:我也不清楚,但你仍然可以使用正常的字符串分割,只是墊空間兩側,如果他的目標是隻刪除單詞「是」。 – ahawker 2009-07-14 17:57:52

+1

這也行不通(至少不是沒有更多的努力),因爲你不知道空間應該在左邊,右邊還是兩邊都出現,而不知道被分割的單詞的位置串。 – IRBMe 2009-07-14 18:03:31

+0

似乎過於複雜,因爲String.Splity可以讓你在一個字符串上分割... – 2009-07-14 18:51:16

4

您可以使用與string.replace()來取代你所需的分割字符串不字符串中出現,然後用字符串的字符。對該字符進行分割以分割相同效果的結果字符串。

25
string s = "This is a sentence."; 
string[] res = s.Split(new string[]{ " is " }, StringSplitOptions.None); 

for(int i=0; i<res.length; i++) 
    Console.Write(res[i]); 

編輯:「是」是爲了保護你想要的單詞的事實填補雙方在陣列中的空間「是」從句子和單詞刪除「本」保持完好。

-5
string strData = "This is much easier" 
int intDelimiterIndx = strData.IndexOf("is"); 
int intDelimiterLength = "is".Length; 
str1 = strData.Substring(0, intDelimiterIndx); 
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength)); 
27

基於這個帖子上現有的響應,這簡化了實現:)

namespace System 
{ 
    public static class BaseTypesExtensions 
    { 
     /// <summary> 
     /// Just a simple wrapper to simplify the process of splitting a string using another string as a separator 
     /// </summary> 
     /// <param name="s"></param> 
     /// <param name="pattern"></param> 
     /// <returns></returns> 
     public static string[] Split(this string s, string separator) 
     { 
      return s.Split(new string[] { separator }, StringSplitOptions.None); 
     } 


    } 
} 
4

...總之:

string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None); 
3

或者使用此代碼; (同樣,新的String [])

.Split(new[] { "Test Test" }, StringSplitOptions.None) 
相關問題