用C 中的另乙個字串分割乙個字串

2021-10-01 20:20:21 字數 2517 閱讀 3638

我一直在使用split()方法來拆分字串,但這僅在按字元拆分字串時才起作用。 有沒有辦法分割乙個string,另乙個字串是按引數分割?

我試過將拆分器轉換為字元陣列,但是沒有運氣。

換句話說,我想分割string

thexxquickxxbrownxxfox

通過xx,並返回具有值的陣列:

the,quick,brown,fox

我通常喜歡使用自己的副檔名:

string data = "thexxquickxxbrownxxfox";

var dataspt = data.split("xx");

//>the quick brown fox

//the extension class must be declared as static

public static class stringextension

, stringsplitoptions.none);

}}

但是,如果microsoft決定在更高版本中包括此方法過載,則會導致異常。 這也是microsoft同時未包含此方法的可能原因:我工作過的至少一家公司在其所有c#專案中都使用了這種擴充套件。

如果該方法不存在,則有可能在執行時有條件地定義該方法。

為了按字串分割,您必須使用字串陣列過載 。

string data = "thexxquickxxbrownxxfox";

return data.split(new string , stringsplitoptions.none);

regex.split(string, "xx")
通常是我這樣做的方式。 當然,您需要乙個

using system.text.regularexpressions;
但是我又一直需要那個圖書館。

有乙個字串拆分的過載 。

"thexxquickxxbrownxxfox".split(new  , stringsplitoptions.none);
您可以使用這些stringsplitoptions中的任何乙個

因此,如果字串為「 thexxquick***xbrownxxfox」,則stringsplitoptions.none將在陣列中為「 ***x」部分返回乙個空條目,而stringsplitoptions.removeemptyentries則不會。

為此有乙個string.split的過載:

"thexxquickxxbrownxxfox".split(new  , stringsplitoptions.none);
最簡單的方法是使用string.replace

string mystring = "thexxquickxxbrownxxfox";

mystring = mystring.replace("xx", ", ");

或更簡單地說:

string mystring = "thexxquickxxbrownxxfox".replace("xx", ", ");
string data = "thexxquickxxbrownxxfox";

return data.replace("xx","|").split('|');

只需仔細選擇替換字元(選擇字串中不太可能存在的替換字元)即可!

先前的答案都是正確的。 我更進一步,通過在string上定義擴充套件方法,使c#為我工作:

public static string split(this string tosplit, string spliton) , stringsplitoptions.none);

}

這樣,我可以以我第一次嘗試完成此操作時幼稚的簡單方式在任何字串上呼叫它:

"a big long string with stuff to split on".split("g str");
這也很容易:

string data = "thexxquickxxbrownxxfox";

string arr = data.split("xx".tochararray(), stringsplitoptions.removeemptyentries);

從.net core 2.0開始,有乙個覆蓋字串的替代項。

因此,現在您可以執行"thexxquickxxbrownxxfox".split("xx")

請參閱

php判斷乙個字串包含另乙個字串

a 58252,58253 如果 a 中存在 b,則為 true 否則為 false。b 58253 if strpos a,b false else 查詢字串在陣列中出現的次數 array array 1,hello 1,world hello 11 計算 string在 array 需為陣列 中...

判斷乙個字串是否在另乙個字串中

方法一 string str1 nihaoksdoksad string str2 ok int total 0 for string tmp str1 tmp null tmp.length str2.length tmp tmp.substring 1 system.out.println st...

判斷乙個字串是否在另乙個字串中

find in set str,str1 判定str是否在str1中有,如果有,則返回其在str1中的位置,如果沒有,返回0 eg select find in set 13教 瀏陽基地,耕耘基地,文淵館,13教,測試基地,耕耘基地 返回4 這個函式有很大的侷限性,他只能判別是否存在於第二個字串中以...