首頁  >  文章  >  後端開發  >  C++中的字串處理技巧

C++中的字串處理技巧

WBOY
WBOY原創
2023-08-22 16:34:461454瀏覽

C++中的字串處理技巧

在C 中,字串(string)是一個非常常見的資料型別。而且,字串處理在程式設計中也是一個非常重要的環節。本文將介紹一些常用的C 中字串處理的技巧,希望對讀者有幫助。

一、C 中的字串類別

在C 中,string是一個類,包含在頭檔中。 string類別中有很多成員函數,下面介紹幾個常用的成員函數:

1、append()函數:用於將一個字串新增到另一個字串尾部。

例如:

string str1 = "Hello";

string str2 = " World";

str1.append(str2);

cout

2、length()函數:用來取得字串的長度。

例如:

string str = "Hello World";

int len = str.length(); //len變數儲存的值為11

#3、substr()函數:用於截取字串的一部分。

例如:

string str = "Hello World";

string s = str.substr(6, 5); //從字串的第6個字符開始,截取長度為5的子字串

cout

4、erase()函數:用於刪除字串的一部分。

例如:

string str = "Hello World";

#str.erase(5, 6); //刪除字串中第5個字元開始,長度為6的子字串

cout

二、字串的遍歷

1、使用下標存取:

使用下標存取字串的每個元素。

例如:

string str = "Hello World";

for (int i = 0; i

cout << str[i] << " ";

}

輸出結果為:

H e l l o W o r l d

2、使用迭代器:

使用C 中的迭代器( iterator),可以方便地對字串進行遍歷。

例如:

string str = "Hello World";

for (string::iterator it = str.begin(); it != str.end() ; it) {

cout << *it << " ";

}

輸出結果為:

H e l l o W o r l d

##三、字串的拆分和合併

1、字串的拆分:

可以使用stringstream類別的對象,將字串依照某個分隔符號進行拆分。

例如:

string str = "Hello World, This is a good day!";

stringstream ss(str);

#string s;

while (getline(ss, s, ',')) {

cout << s << endl;

}

#輸出結果為:

Hello World

#This is a good day!

2、字串的合併:

可以使用stringstream類別的對象,將多個字串進行合併。

例如:

stringstream ss;

string s1 = "Hello";

string s2 = " World!";

# ss string s = ss.str();

cout 輸出結果為:

Hello World!

四、其他常用函數

#1、atoi()函數:

將字串轉換為整數。

例如:

char a[] = "1234";

int b = atoi(a);

cout 2、atof()函數:

將字串轉換為浮點數。

例如:

char a[] = "12.34";

float b = atof(a);

cout 3、strcmp()函數:

比較兩個字串的大小。

例如:

char str1[] = "Hello";

#char str2[] = "World";

int res = strcmp(str1 , str2);

cout 4、strstr()函數:

#找出字串中是否包含另一個字串。

例如:

char haystack[] = "Hello World";

char needle[] = "Wo";

char *res = strstr (haystack, needle);

cout 注意:傳回值為指向首次出現的子字串的指標。

以上是C 常用的字串處理技巧,希望可以幫助大家。當然,還有很多其他的技巧和函數可以用來處理字串,需要不斷學習和實踐。

以上是C++中的字串處理技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn