1. string中npos , find , substr ,c_str的使用。
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
//找到字符串中,字符":"后面的数字并输出
void find_number(string &s)
{
int pos=s.find(":");
//string::npos代表字符串的末尾
if(pos==(int)string::npos)
cout<<"没有"<<endl;
else{
string str=s.substr(pos+1,s.length()-1);//substr(int pos,int len),参数pos代表所复制string的开始位置,len为复制长度
//cout<<atoi(str)<<endl;//本条语句错误,atoi的参数是c标准字符串的首地址
cout<<atoi(str.c_str())<<endl;//c_str()返回一个string类型的c标准字符串的首地址
cout<<atoi(&str[0])<<endl;//直接利用这个方式似乎也可以得到
}
}
int main()
{
string str="What your :678";
string str1="why";
find_number(str);
find_number(str1);
return 0;
}

3721

被折叠的 条评论
为什么被折叠?



