一、截取单个字符串
在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;
}