CCF第三题字符串处理stl函数及正则表达式
c++中常用的字符串处理方法及函数
这部分会举几个实例简单介绍一下,比较常见的库函数用法。表示本人也是一个刚学C++不久的人,对各种库函数完全不熟。所以借着刷CCF顺便把做题常用的字符串处理方法和函数整理一下。
一、sting类的输入输出
- cin>>str,cout<<str ,string类重载运算符;
- getline(istream &in,string &s), 用于从输入流in中读取字符串到s中,以换行符’\n’分开。如,getline(cin,str);
cin遇到空格会停止,所以如果要输入含空格的字符串,要用getline
二、子串的处理
1.子串的获取
- substr(int pos = 0,int n = npos) const,返回pos开始的n个字符组成的字符串,如
str.substr(0,5)
,获取从第0个字符开始的5个字符。
string str = "#abcd";
string r = str.substr(0,1); //r="#";
- erase(intpos = 0,int n = npos) const,擦除从pos开始的npos个字符。
string str = "12345";
str.erase(0,3); //擦除从1开始的3个字符,str = "45"
str.erase(1,1); //str = "1345"
str.erase(1); //擦除从第1个字符开始的所有字符,str = "1"
2.子串的查找
- find,查找子串
int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
string str = "a b c d";
int pos = str.find(' '); //返回空格的位置,pos = 1;
- find_first_of,查找字符c第一次在字符串中出现的位置,如果不存在则返回-1
string str = "a b c d";
int pos = str.find_first_of(' '); //pos = 1;
- find_first_not_of,查找字符串中第一个不是字符c的字符位置,一般可以配合erase来使用,用来处理字符串前缀
string str = "....abcd";
int pos = str.find_first_not_of('.'); //pos = 4
str.erase(0,str.find_first_not_of('.')); //去掉前缀‘.’,str = "abcd"
- find_last_of
- find_last_not_of
5.按空格拆分字符串,存入数组
1)stl
#include <iostream>
#include <string>
#include <sstream>
string str = "hello world!";
string strarry[10];
stringstream ss(str);
int cnum = 0;
while (ss >> strarry[cnum]) {
cnum++;
}
2)正则表达式(sregex_token_iterator)
regex split("\\s");
sregex_token_iterator
p(str.begin(),str.end(),split,-1);
sregex_token_iterator end;
vector<string> words;
while(p!=end){
words.push_back(*p++);
}
6.去掉字符串首尾空格
1)stl(erase,find)
s.erase(0,s.find_first_not_of(' '));//erase(pos,len)
s.erase(s.find_last_not_of(' ')+1,s.size());
2)正则表达式
regex htblank("^\\s+|\\s+$");
str = regex_replace(str,htblank,"");
7.字符串中连续空格变为单个空格
1.stl(find,replace)
//stl
int pos = s.find(" ");
while(pos!=-1){
s.replace(pos,2," ");
pos = s.find(" ");
}
2.正则表达式
regex midblank("\\s{2,}");
str = regex_replace(str,midblank," ");
8.提取字符串中的字母、数字
regex notword("\\W");
sregex_token_iterator
p(s.begin(),s.end(),notword,-1);
sregex_token_iterator end;
string result;
while(p!=end){
result += *p++;
}
//一定要用新的字符串保存*p
/*原因:程序员负责确保传递给迭代器构造函数的 std::basic_regex 对象活得长于迭代器。因为迭代器存储指向 regex 的指针,故在销毁 regex 后自增迭代器会访问悬垂指针。*/
/*作者把s.clear()重用,结果就是第一个字符会变成空格,蜜汁调了很久*/
三、字符的处理
1.大小写转换
使用#include 里的transform(str.begin(),str.end(),str.begin(),::tolower),参考c++中常用的大小写转换
#include <string>
#include <algorithm>
string str1,str2;
str1 = "ABcdEFG";
str2 = "ABcdEFG";
//change str1 to "abcdefg"
transform(str1.begin(),str1.end(),str1.begin(),::tolower);
//change str2 to "ABCDEFG"
transform(str2.begin(),str2.end(),str2.begin(),::toupper);