C++字符串操作

去除两端空白符

利用正则表达式匹配替换

string line = " hello, world!\t\t  ";
line = regex_replace(line, regex("^\\s+|\\s+$"), ""); // 匹配line两端的空白符,并替换为空串

按指定字符分割字符串

利用std::getline,其默认以换行符分割

vector<string> getTokens(const string& line, const char delimiter) {
istringstream iss(line);
vector<string> tokens;
string token;
while (getline(iss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}

string line = "abcd-5555-pppp";
getTokens(line, '-');

注:istringstream以空白符分割字符串来构造流且不可改,可以利用getline为其多传入一个分隔符参数来从流中按指定分隔符读入字符串,以达到分割字符串的目的;如果就是准备以单个空格分割字符串,也可以直接用iss >> token代替getline(iss, token, ' '),注意getline的参数' '不可省,因为其默认以换行符分割

string的几种构造方式

  1. 直接声明构造空串
string s; // ""
  1. 按字面量初始化
string s1 = "cpp";
string s2("cpp"); // 两种的效果是一样的
  1. 重复用特定字符构造
string s3(5, 'a'); // "aaaaa"
string s4(1, 'a'); // "a", 可以视作字符->字符串
  1. 获得子串

string::substr方法,第一个参数为字串起始位置,第二个参数若缺省则取后面所有,否则代表子串的长度

string s5 = "hello,cpp";
string hello = s5.substr(0, 5); // "hello"
string cpp = s5.substr(6); // "cpp"

拼接字符串

+

不改变原串

append

改变原串

示例:

string s1 = "abc", s2 = "def";
string s3 = s1 + s2;
cout << s1 << " " << s2 << endl; // abc def
s1.append(s2);
cout << s1 << endl; // abcdef

查找子串

string::find可用于字符串中查找子串的位置

std::string str = "Hello, world!";
size_t pos = str.find("world"); // 查找子串 "world" 在字符串中的位置
if (pos != std::string::npos) { // 用这个判断是否找到
std::cout << pos << std::endl; // 7
}

查找字符

仍用string::find

std::string str = "Hello, world!";
size_t pos = str.find('o'); // 查找字符 'o' 在字符串中第一次出现的的位置

查找最后一个子串

string::rfind

std::string str = "Hello, world!";
size_t pos = str.rfind("world"); // 查找最后一次出现 "world" 的位置

字符串替换

string::replace

std::string str = "Hello, world!";
str.replace(7, 5, "C++"); // 从位置 7 开始,替换 5 个字符为 "C++"

正则替换

先用std::regex正则匹配,再用std::regex_replace替换

std::string str = "Hello, world!";
std::string result = std::regex_replace(str, std::regex("world"), "C++"); // 将"world"替换为"C++"

(•‿•)