头文件机命名空间:
#include<string>
using namespace std;
遍历试用的下标类型:
string::size_type类型描述的是string类型中下标的类型。所以遍历string类型的方法是:
for(string::size_type i=0;i<obj.size;i++) //因为长度不确定,所以i的类型就没办法确定,只能用string::size_type类型
{
cout<<obj[i]<<endl; //变量string对象的每一个成员
}
obj.c_str()返回的是const char*类型的指针,表明不能对这段空间进行其他方式赋值
注意:
obj[i]表示obj字符串中的第i+1个字符
string类的常用操作接口:
string类的更多操作:
1.创建string对象的方法:string str;
string str("hello world");
string str="hello world";
string str(obj); string str=obj;
2.将string类中字符串的首地址返回:(返回string类型字符串的首地址,即和c字符串的转换,c_str)
const char *p;
p=str.c_str();
3.判断string类对像是否为空:
string str;
str.empty() //为空返回true,否则返回false
4.获取string类对象中字符的个数:(字符串预设长度,size()和length,strlen(*.c_str()) )
string::size_type size;
str.resize(number); //预设字符串中存储number个字节。但并不是实际就number个,也并不是说实际只能存number个
size=str.size(); //获取字符串预设长度str
size=str.length();
举例:
string str;
str.resize(100);
str[0]='a';
str[1]='b';
str[2]='\0';
cout<<str.size()<<endl; //运行结果是100
cout<<str.length()<<endl; //运行结果是100
cout<<strlen(str.c_str())<<endl; //运行结果是2,字符串的真正长度
5.字符串连接的两种方法:
方法一:
string str1("hello");
string str2("world");
str1+=str2;
方法二:
str1.append(str2);
6.向字符串中插入一个字符串:
string str("hello world");
str.insert(pos,"billchen"); //在字符串下标为pos的地方插入字符串"billchen".
注意:替换字符串replace相当于erase删除子串,然后再insert插入子串。
7.删除字符串中的一个子串:
string str("hello world");
str.erase(pos,length); //将str字符串中下标从pos开始的长度为len的一个子串删除。
注意:清空字符串 str.clear();
8.替换字符串中的一个子串:
string str("hello world");
str. replace(pos,len,args); //将str字符串中下标从pos开始的长度为len的一个子串删除,使用args指向的字符串代替。
9.查找字符串中某个子串出现的位置:
string str("hello world");
str.find("wo"); //在str中查找"wo"第一次出现的位置的下标
str,rfind("wo"); //在str中查找"wo"最后一次出现的位置的下标
if(ops==string::npos)
{
out<<"没有找到"<<endl;
}
str.find_first_of(args); //在str中查找args的任意字符的第一次出现。
str.find_last_of(args); //在str中查找args的任意字符的最后一次出现。
str.find_first_no_of(args); //在str中查找第一个不属于args的字符。
str.find_last_no_of(args); //在str中查找最后一个不属于args的字符。
注意:string类得find方法的返回值是size_type类型。
当没有查找到时,返回值是string::npos
10.下标法遍历
string str("hello world");
string::size_type i;
for(i=0;i<=str.size();i++)
{
cout<<"str[i]"<<" ";
}
11.迭代器遍历
string str("hello world");
string::interator iter=str.begin();
while(iter!=str.end())
{
cout<<*iter<<" ";
iter++;
}
12.从字符串中截取子串:
string str("hello world");
str.substr(pos,n); //从pos开始,长度为n的一个子串
str.substr(pos); //截取下标从pos开始到字符串末尾的子串