添加头文件
#include
<string>
利用构造函数的初始化方法
string a="aaa";
string b(a.size(),'b');//全是字符b
cout<<b;
str.insert()方法插入 str.clear()清空
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int main(){
string str="hello";//初始化
int n=str.size(); cout<<n<<endl;//.size()字符串长度
for(int i=0;i<n;i++){//像数组访问元素 从0到size-1
cout<<str[i];
}
cout<<endl;
//任意位置插入insert() 任意位置删除erase() 清空clear()
str.insert(5," hello"); cout<<str<<endl;
str.clear(); cout<<str;
}
str .erase()方法 删除
第一个参数为位置参数 第二个参数为数量
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "hello c++! +++";
// 从位置pos=10处开始删除,直到结尾
// 即: " +++"
str.erase(10);
cout << '-' << str << '-' << endl;
// 从位置pos=6处开始,删除4个字符
// 即: "c++!"
str.erase(6, 4);
cout << '-' << str << '-' << endl;
return 0;
}
运算符+ < > <= >= != ==
string常用函数 find() substr()
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int main(){
//str.substr
string str="hello";//初始化
string str2=str.substr(2,3);//llo 第一个参数定位 第二个参数数量
cout<<str2<<endl;
//str.find
//若找到则返回下标 否则返回string::npos
int n=str.find("lo"); cout<<n<<endl;
n=str.find("ol"); if(n==string::npos) cout<<"not find";
}
string分割字符串 find() substr()
for(int i=0;i<n;i++){//!!!分割 !!!
vs.clear();
int begin=0,end=0;//begin end
end=v[i].find("\\",begin);//
while(end!=string::npos){//
vs.push_back(v[i].substr(begin,end-begin));
begin=end+1;
end=v[i].find("\\",begin);
}
ve.push_back(vs);
}
char数组 用strtok()分割字符串
char *strtok(char s[], const char *delim);
s为要分解的字符,delim为分隔符字符(如果传入字符串,则传入的字符串中每个字符均为分割符)。
首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
返回值:从s开头开始的一个个被分割的串。当s中的字符查找到末尾时,返回NULL。
tip:用此函数会改变原字符串 因为它会将分隔符变为’\0’
#include <string.h>
#include <stdio.h>
int main () {
char str[80] = "This is - www.runoob.com - website";
const char s[2] = "-";
char *token;
/* 获取第一个子字符串 */
token = strtok(str, s);
/* 继续获取其他的子字符串 */
while( token != NULL ) {
printf( "%s\n", token );
token = strtok(NULL, s);
}
return(0);
}
KMP(只匹配一次/一直匹配至结束)
#include<csdtio>
#include<iostream>
#include<cstring>
int pattern[1000];
int text[1000];
int nextTable[1000];
void GetNextTable(int m){
int j=0; i=-1;
nextTable[j]=i;
while(j<m){
if(i==-1||pattern[i]==pattern[j]){
i++;
j++;
nextTable[j]=i;
}
else{
i=nextTable[i];
}
}
}
int KMP(int n,int m){
GetNextTable(m);
int i=0; int j=0;
while(i<n&&j<m){
if(j==-1||pattern[i]==pattern[j]){
i++;
j++;
}
else{
j=nextTable[j];
}
}
if(j==m) return i-j+1;
else return 0
}