申明:str1、str2为string类型, c1, c2为字符数组
1.字符串长度
str1.length(); strlen(c1);
2.字符串后加文本
str1.append(str2) 在str1的末尾添加str2;
对应c函数strcat(c1, c2),返回指针c1
str1.append(num, ch) 在字符串的末尾添加num个字符ch
3.字符串和字符数组相互转换
字符数组转化为字符串: str1=c1; 或者 string str1(c1,c1+n);
字符串转化为字符数组: strcpy(c1, str1.c_str());
4.字符串搜寻(未找到返回string::npos)
str1.find(str2, index) 在str1里找str2,从index开始找 (index默认为0)
对应c函数strstr(c1, c2) 在c1里找c2, 返回一个指针,未找到返回NULL
str1.find(ch, index)
对应c函数strchr(c1, ch) 在c1里找ch,返回一个指针,未找到返回NULL
还有一个用法完全一致的函数rfind(), 唯一不同点是这个函数是从后往前找
5.字符串删除
str1.erase(index, num)
str1.erase(index)
6.字符串插入
str1.insert(index, str2)
str1.insert(index, num, ch)
7.字符串替换
str1.replace(index, num, str2) 用str2替换str1的字符,从index开始,最多num个字符
str1.replace(index, num1, num2, ch)
8.字符串子串
str1.substr(index, num)
str1.substr(index)