字串分割(c++)
經常碰到字串分割的問題,這裡總結下,也方便我以後使用。
一、用strtok函式進行字串分割
原型: char *strtok(char *str, const char *delim);
功能:分解字串為一組字串。
引數說明:str為要分解的字串,delim為分隔符字串。
返回值:從str開頭開始的乙個個被分割的串。當沒有被分割的串時則返回null。
示例: 1 //借助strtok實現split
2 #include
3 #include
4 5 int main()
6 執行效果:
二、用stl進行字串的分割
涉及到string類的兩個函式find和substr:
1、find函式
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查詢子字串第一次出現的位置。
引數說明:str為子字串,pos為初始查詢位置。
返回值:找到的話返回第一次出現的位置,否則返回string::npos
2、substr函式
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:獲得子字串。
引數說明:pos為起始位置(預設為0),n為結束位置(預設為npos)
返回值:子字串
實現如下:
1 //字串分割函式
2 std::vector split(std::string str,std::string pattern)
3 完整**:
view code
1 //本程式實現的是利用正規表示式對字串實現分割
2 //執行環境 vc6.0 + boost 庫
3 /*
4 file : split2.cpp
5 author : mike
6 e-mail : mike_ 7 */
8 #include
9 #include
10 #include
11 #include
12 #include "boost/regex.hpp"
13 14 std::vector split(std::string str,std::string s)
15 26 int main()
27 {
28 std::string str,s;
29 str="sss/ddd/ggg/hh";
30 s="/";
31 std::vector vec=split(str,s);
32 for(int i=0,size=vec.size();i執行效果:
好,就這些了,希望對你有幫助。
js字串方法
關鍵字 js字串方法 js js自帶函式 concat 將兩個或多個字元的文字組合起來,返回乙個新的字串。vara hello varb world varc alert c c hello,world indexof 返回字串中乙個子串第一處出現的索引 從左到右搜尋 如果沒有匹配項,返回 1。va...
js字串方法
關鍵字 js字串方法 js js自帶函式 concat 將兩個或多個字元的文字組合起來,返回乙個新的字串。vara hello varb world varc alert c c hello,world indexof 返回字串中乙個子串第一處出現的索引 從左到右搜尋 如果沒有匹配項,返回 1。va...
Java字串使用總結
除非另行說明,否則將 null 引數傳遞給此類中的構造方法或方法都會丟擲 nullpointerexception。string 表示乙個 utf 16 格式的字串,其中的增補字元由 項對表示 有關詳細資訊,請參閱 character 類中的 unicode 字元表示形式 索引值是指 char 單元...