字符串笔记

1字符数组输入

char buf[100];
fgets(buf,100,stdin);//可读取一整行元素,但包含换行符\n

2.字符串和字符数组转换

char buf[100];
scanf("%s",buf);
string str = buf;//将字符数组生成一个C++风格的字符串
printf("str=%s\n',str.c_str());//将C++风格的字符串转换为字符数组

3.字符串长度

string str;
str.size()//字符串长度,例:hello,size=5,length=5;
str.length();

4.访问每个字符

访问每个字符
string s;
cin>>s;
for(int i=0;i<s.size();i++){
 printf("%c\n",s[i]);
 }

string str;
cin>>str;
for(string::iterator it=str.begin();it!=str.end();it++){//采用迭代器
printf("%c\n",*it);
}

例:

char s[110];
cin.getline(s,110);
cout<<strlen(s)<<endl;
string a=s;
cout<<a.size()<<endl;
cout<<a.length();
输入:hello hello
输出为:
11
11
11



char s[110];
fgets(s,110,stdin);
cout<<strlen(s)<<endl;
string a=s;
cout<<a.size()<<endl;
cout<<a.length();
输入:hello hello
输出为:
12//因为包含最后的换行符
12
12

5.应用
连接:+
删除:s.erase()//删除从第几个位置之后的元素
清空:s.clear()
查找:s.find()
查找成功返回查找到的起始下标
查找失败返回string::npos

string a;
cin>>a;
a=a+"world";
cout<<a<<endl;
a.erase(7);
cout<<a<<endl;
int pos=a.find("are");
if(pos!=string::npos)
	cout<<"Found,pos="<<pos<<endl;
else cout<<"Not Found!"<<endl;
pos=a.find("wo");
if(pos!=string::npos)
	cout<<"Found,pos="<<pos<<endl;
else cout<<"Not Found!"<<endl;
	
输入:hello
输出:helloworld
hellowo
Not Found!
Found,pos=5

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值