一、截取單個字元串
在C++中,要截取單個字元串需要使用substr函數。substr函數的原型為:
string substr (size_t pos, size_t len) const;
其中,pos為截取的起始位置,len為截取的長度。
例如,有一個字元串str = “hello world”,如果要截取”world”這個單詞,可以使用下面的代碼:
string str = "hello world";
string s = str.substr(6, 5); // s為"world"
二、分割字元串
在進行文本處理時,我們通常需要將一個長字元串分割為若干個子字元串,以便對每個子字元串進行分析處理。
在C++中,實現分割字元串的方法有很多種,下面介紹兩種常用的方法。
1、使用stringstream
stringstream是一個方便的字元串流類,可以將一個字元串視為流,從而方便地進行字元串處理。
例如,有一個字元串str = “apple,banana,orange”,需要將它分割成3個單詞,並存儲到一個vector中,可以使用下面的代碼:
string str = "apple,banana,orange";
vector<string> v;
stringstream ss(str);
string word;
while (getline(ss, word, ',')) {
v.push_back(word);
}
其中,getline函數可以從字元串ss中讀取以’,’為分隔符的單詞,並將其存儲到word中。
2、使用string的find和substr函數
另一種分割字元串的方法是使用string的find和substr函數,該方法基於尋找特定的分隔符來分割字元串。
例如,有一個字元串str = “apple,banana,orange”,需要將它分割成3個單詞,並存儲到一個vector中,可以使用下面的代碼:
string str = "apple,banana,orange";
vector<string> v;
size_t pos = 0;
string token;
while ((pos = str.find(',')) != string::npos) {
token = str.substr(0, pos);
v.push_back(token);
str.erase(0, pos + 1);
}
v.push_back(str);
其中,find函數可以查找特定字元的位置,substr函數可以從字元串中截取某一段字元。
三、刪除字元串中的空格
在進行文本處理時,通常需要刪除字元串中的空格,以便更好地進行分析處理。在C++中,實現刪除字元串中空格的方法也有很多種,下面介紹一種常用的方法:
使用STL演算法
使用STL演算法中的remove和erase函數可以輕鬆刪除字元串中的空格。
例如,有一個字元串str = “hello world”,需要將其中的空格刪除,可以使用下面的代碼:
string str = "hello world";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
其中,remove函數可以將字元串中的空格移到末尾,並返回指向最後一個空格的迭代器,同時,erase函數可以將末尾的空格刪除。使用這兩個函數的組合,可以快速刪除字元串中的空格。
完整示例代碼:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
void test_substr() {
string str = "hello world";
string s = str.substr(6, 5); // s為"world"
cout << s << endl;
}
void test_split() {
string str = "apple,banana,orange";
vector<string> v;
stringstream ss(str);
string word;
while (getline(ss, word, ',')) {
v.push_back(word);
}
for (string s : v) {
cout << s << endl;
}
}
void test_split2() {
string str = "apple,banana,orange";
vector<string> v;
size_t pos = 0;
string token;
while ((pos = str.find(',')) != string::npos) {
token = str.substr(0, pos);
v.push_back(token);
str.erase(0, pos + 1);
}
v.push_back(str);
for (string s : v) {
cout << s << endl;
}
}
void test_remove_spaces() {
string str = "hello world";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
cout << str << endl;
}
int main() {
test_substr();
test_split();
test_split2();
test_remove_spaces();
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/280651.html