目录
橙色
一些针对c语言风格的字符数组操作的函数
strcpy(str2,str1)就是把str1复制到str2中
strcmp(str1,str2),str1更大,则返回1;str2更大,则返回-1;相等,则返回0。
strcat(str1,str2),把str2接在str1的后面
strupr(str),str为字符数组的首地址,其实也就是字符数组名。可以将该字符数组中的所有字符变为大写字母,数字是不会有变化的。
string字符串转换为c风格的字符数组需要利用string类成员函数c_str()。而c风格字符数组转换为string字符串则可以直接利用运算符=。
#include<iostream>
#include<string>
using namespace std;
int main(){
string str="hello";
const char *ch;
ch = str.c_str();
cout << ch << endl;
ch = "world";
str = ch;
cout << str << endl;
return 0;
}
一些针对string字符串操作的函数
比较string
一种方法是直接用运算符!=,>=这种,另一种方式就是用string类的成员函数compare(),一般形式是str1.compare(str2),完全相等的话就返回0
查找string的某个元素
#include<time.h>
#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "hello;;w";
char ch = ';';
cout << "元素ch位于字符串str的第" << str.find(ch) << "位" << endl;
cout << str.find_first_not_of(ch) << endl; //向后找不是ch字符的第一个位置
cout << str.find_first_of(ch) << endl; //第一个是ch字符的位置
cout << str.find_last_not_of(ch) << endl; //从后向前找不是ch字符的位置
cout << str.find_last_of(ch) << endl; //从后向前找是ch字符的位置
cout << str.rfind(ch) << endl; //从后向前找ch的首个位置
return 0;
}
这些方法不仅可以查找某字符在字符串中的位置,也可以查找某字符串在另一个字符串中的位置
检测string字符串是否为空
str.empty();
获取string字符串的长度
str.length();
提取string字符串中的子串
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "helloworld";
string sub_str = "";
sub_str = str.substr(0, 5); //提取str从位置0开始长度为5的子串
cout << sub_str<< endl;
return 0;
}
把两个string字符串相加
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1 = "i love ";
string str2 = "china";
string str3 = str1+str2; //提取str从位置0开始长度为5的子串
cout << str3<< endl;
return 0;
}
string字符串和c语言风格的字符数组相加
- 两者可以直接相加,返回值类型为string
- 利用成员函数append()完成相加
string字符串与单字符相加
利用运算符+即可
string字符串替换
#include<iostream>
#include<string>
using namespace std;
int main() {
string str = "hello world";
string str1 = "c++";
str.replace(6,5,str1); //提取str从位置0开始长度为5的子串
cout << str << endl;
return 0;
}