C 中使用split分割字串的幾種方法

2021-05-22 08:56:07 字數 1658 閱讀 1671

來自:http://www.cnblogs.com/tmouse/articles/259747.html

第一種方法:

string s=abcdeabcdeabcde;

string sarray=s.split(c) ;

foreach(string i in sarray)

console.writeline(i.tostring());

輸出下面的結果:

abdeab

deab

de第二種方法:

我們看到了結果是以乙個指定的字元進行的分割。使用另一種構造方法對多個字元進行分割:

string s=abcdeabcdeabcde

string sarray1=s.split(new char[3]) ;

foreach(string i in sarray1)

console.writeline(i.tostring());

可以輸出下面的結果:

abab

ab第三種方法:

除了以上的這兩種方法以外,第三種方法是使用正規表示式。新建乙個控制台專案。然後先新增 using system.text.regularexpressions;

system.text.regularexpressions

string content=agcsmallmacsmallgggsmallytx;

stringresultstring=regex.split(content,small,regexoptions.ignorecase)

foreach(string i in resultstring)

console.writeline(i.tostring());

輸出下面的結果:

agcmac

gggytx

第四種方法:

string str1=我*****是*****一*****個*****教*****師;

string str2;

str1=str1.replace(*****,*) ;

str2=str1.split(*) ;

foreach(string i in str2)

console.writeline(i.tostring());

第五種方法:

string str1=我**是*****一*****個*****教*****師;

我 希望顯示的結果為:我是乙個教師。

我如果採用上面的第四種方法來做就會產生下面的錯誤:我   是乙個教師。中間有空格輸出,所以輸出結果並不是希望的結果,這就又回到了正規表示式了,這時可以採用下面的第五種方法:

string str1=我**是*****一*****個*****教*****師;

string str2 = system.text.regularexpressions.regex.split(str1,@[*]+);

foreach(string i in str2)

console.writeline(i.tostring());

這裡通過[*]+ 巧妙的完成了我們的目標。

split分割字串

string tmp weekcode.split new char string yr tmp 0 string wk tmp 1 string tmp regex.split eachl,error regexoptions.ignorecase 用字串來分割 error 把 以 error 為...

字串分割split

知識講解 split 方法將字串分割為字串陣列,並返回此陣列。stringobject.split separator,limit 注意 如果把空字串 用作 separator,那麼 stringobject 中的每個字元之間都會被分割。我們將按照不同的方式來分割字串 使用指定符號分割字串,如下 v...

Python字串 字串分割 split

python split 通過指定分隔符對字串進行切片,如果引數num 有指定值,則僅分隔 num 個子字串 str.split str num string.count str 引數str 分隔符,預設為所有的空字元,包括空格 換行 n 製表符 t 等。num 分割次數。usr bin pytho...