1) 在中,size()与length()的实现是一样的,都返回string的长度
2) 截取部分字符串
string.substr(beginPose,endPose)
string line = "(a,b,c,d)";
line = line.substr(1,line.size()-2);
// line == "a,b,c,d"
1) geiline:https://www.cnblogs.com/xiaofeiIDO/p/8574042.html
#include<iostream>
#include<string>
string text;
std::getline(std::cin,text);
ifstream inFile;
inFile.open("Hello.txt", ios::in);
if(!inFile.is_open())
return false;
while(std::getline(inFile,text)){
/* code */
}
简单算法的实现
1) KMP
int* getNext(string p)
{
int* next = new int[p.length()];
next[0] = -1; //while the first char not match, i++,j++
int j = 0;
int k = -1;
while (j < (int)p.length() - 1)
{
if (k == -1 || p[j] == p[k])
{
j++;
k++;
next[j] = k;
}else{
k = next[k];
}
}
return next;
}
int KMP(string ts,string ps)
{
int i=0;
int j=0;
int* next=getNext(ps);
while (i < (int)ts.length() && j < (int)ps.length())
{
if (j == -1 || ts[i] == ps[j])
{
i++;
j++;
}else{
j=next[j];
}
}
if (j == (int)ps.length()){
return i-j;
}
return -1;
}
2) 字符串分割
substr(起始位置,需要分割的长度);
/*字符串分割算法*/
vector<string> splitOnce(const string& line, const string& op){
vector<string> result;
/*使用KMP算法匹配字符串*/
int pose = KMP(line,op);
result.push_back(line.substr(0,pose));
result.push_back(line.substr(pose+op.size(),line.size()));
return result;
}
vector<string> split(const string& line, const string& op){
vector<string> result;
int pose;
string text(line);
while (true)
{
pose = KMP(text,op);
if(pose == -1)
break;
result.push_back(text.substr(0,pose));
text = text.substr(pose+op.size(),text.size());
}
result.push_back(text);
return result;
}
3) 大小写转换
- 统一转成大写:ch & 0b11011111 简写:ch & 0xDF
- 统一转成小写:ch | 0b00100000 简写:ch | 0x20
if((s.charAt(i ++) & 0xDF) != (s.charAt(j --) & 0xDF)) return false;
STL/alog 函数
1. 反转字符串
string a = "hello";
reverse(a.begin(),a.end()); // olleh