目录
1、C风格字符串
字符数组,以'\0'为结束标志(占空间)。
输入输出函数:scanf()——只能读取一个单词, printf()
2、C++风格字符串
头文件 #include <string>
fgets(字符数组名称,容量,stdin);——读取一整行,包括换行符
#include <cstdio>
#include <string>
using namespace std;
int main(){
char buf[100];//申请一个字符串数组
scanf("%s",buf);//只能读取一个单词,到空格结束
fgets(buf,100,stdin);//读取一整行,包括换行符
string str = buf;//用一个字符数组,生成一个C++风格字符串
printf("length of str = %u\n",str.length());//u:unsigned int, 获取大小
for (unsigned int i=0;i<str.size();i++){
printf("%c\n",str[i]);//访问字符
}
for(string::iterator it = str.begin();it!=str.end();++it){//使用迭代器依次访问
printf("%c\n",*it);//*: 通过地址访问元素。与str[i]效果相同。&:求地址
}
str.erase(0,2);//字符删除,前闭后开区间
str = str + "world";//+在C++风格字符串中表示连接操作
printf("str = %s",str.c_str());//C++风格字符串转为字符数组
}
3、字符串匹配
find()——查找字符或子串
找到:返回起点下标
未找到:返回 string::npos (-1)
#include <cstdio>
#include <string>
using namespace std;
int main(){
string str = "howareyou";
int pos = str.find("wae");
if(pos!=string::npos){//在字符串中出现过
prinf("Found, pos=%d\n",pos);
}else{
prinf("Not found\n");
}
}