一、字符串的基本概念
在C++中,字符串是一個字符數組,可以通過char或string類型來表示。char類型的字符串以空字符作為字符串的結束符,而string類型則沒有這個限制。
要聲明一個字符串變量,可以使用以下方式:
char str[] = "hello world"; string s = "hello world";
可以使用cout輸出字符串變量,如:
cout << str << endl; // 輸出 hello world cout << s << endl; // 輸出 hello world
二、字符串的常用操作
1. 長度
使用strlen函數可以獲取一個字符數組的長度,而使用size()函數可以獲取一個string對象的長度。
char str[] = "hello world"; string s = "hello world"; cout << strlen(str) << endl; // 輸出 11 cout << s.size() << endl; // 輸出 11
2. 拼接
可以使用+運算符或者append函數對字符串進行拼接。
char str1[] = "hello"; char str2[] = " world"; string s1 = "hello"; string s2 = " world"; cout << str1 + str2 << endl; // 輸出 hello world cout << s1 + s2 << endl; // 輸出 hello world s1.append(s2); cout << s1 << endl; // 輸出 hello world
3. 查找
使用find函數可以查找一個字符或者字符串在另一個字符串中的位置。
char str[] = "hello world"; string s = "hello world"; cout << strstr(str, "wor") << endl; // 輸出 world cout << s.find("wor") << endl; // 輸出 6
4. 替換
可以使用replace函數對一個字符串中的某一部分進行替換。
char str[] = "hello world"; string s = "hello world"; str[6] = '\0'; // 將 'w' 替換成空字符 s.replace(6, 1, ""); cout << str << endl; // 輸出 hello cout << s << endl; // 輸出 hello
三、字符串的高級操作
1. 字符串分割
可以使用stringstream將一個字符串按照指定分隔符分割成多個子串。
#include <sstream> #include <vector> using namespace std; string s = "hello,world,how,are,you"; vector<string> tokens; stringstream ss(s); string token; while (getline(ss, token, ',')) { tokens.push_back(token); } for (int i = 0; i < tokens.size(); i++) { cout << tokens[i] << endl; }
輸出:
hello world how are you
2. 字符串去空格
可以使用STL中的algorithm庫進行去空格操作。
#include <algorithm> #include <cctype> using namespace std; string s = " hello world "; s.erase(s.begin(), find_if(s.begin(), s.end(), [](int ch) { return !isspace(ch); })); s.erase(find_if(s.rbegin(), s.rend(), [](int ch) { return !isspace(ch); }).base(), s.end()); cout << s << endl; // 輸出hello world
3. 字符串轉換
可以使用stringstream或者to_string函數將字符串和數字相互轉換。
int a = 123; double b = 3.14; string c = "456"; stringstream ss; ss << a << " " <> x >> y; cout << x << " " << y << endl; // 輸出 123 3.14 int z = stoi(c); cout << z << endl; // 輸出 456
以上就是C++對字符串進行處理和操作的一些常用方法,可以應用於實際開發中。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/240283.html