# include <iostream>
# include <string>
# include <algorithm>
using namespace std;
int main(){
string strSTLString("Hello world");
/*
关于String类型的字符串的输出
*/
//1.
//size_t 就是无符号整数 unsigned int
for(size_t i=0;i<strSTLString.length();i++){
cout<<strSTLString[i];
}
cout<<endl;
//2.
cout<<strSTLString<<endl;
//3.迭代器
string::const_iterator itr;
for(itr=strSTLString.begin();itr!=strSTLString.end();itr++){
cout<<*itr;
}
cout<<endl;
//4.C语言的字符串,c_str()函数返回C语言字符串
cout<<strSTLString.c_str()<<endl;
cout<<"------------------------------"<<endl;
/*
字符串的连接 str2连接到str1的后面
*/
//1.
string str1="AAA";
string str2="BBB";
str1+=str2;
cout<<str1<<endl;
//2. 用append追加
str1.append(str2);
cout<<str1<<endl;
//3.追加C语言数组
char a[4] = "CCC";
//相当于 const char *a = "CCC";
str1.append(a);
cout<<str1<<endl;
/*
在字符串中查找某个字符串或字符
*/
//1.找第一个位置的时候
str1 = "Good day String! Today is beautiful!";
cout<<str1<<endl;
size_t index = str1.find("day",0);//代表从第0个位置开始day字符串
if(index!=string::npos)// npos相当于-1
{
cout<<index<<endl; //输出的是下标
}
else
{
cout<<"没有找到"<<endl;
}
//2.找到字符串中所有的
str1 = "Good day String! Today is beautiful!";
cout<<str1<<endl;
index = str1.find("day",0);//代表从第0个位置开始day字符串
while(index!=string::npos)// npos相当于-1
{
cout<<index<<endl; //输出的是下标
index = str1.find("day",index+1);
}
//3.所有的字符a
str1 = "Good day String! Today is beautiful!";
cout<<str1<<endl;
index = str1.find('a',0);//代表从第0个位置开始day字符串
while(index!=string::npos)// npos相当于-1
{
cout<<index<<endl; //输出的是下标
index = str1.find('a',index+1);
}
//1.
str1 = "Good day String! Today is beautiful!";
cout<<str1<<endl;
cout<<str1.erase(4,10)<<endl; //删除4下标的连续的10个
cout<<str1<<endl;// str1字符串本身发生改变
//2.find算法,迭代器
string::iterator iCharS = find(str1.begin(),str1.end(),'s');//查找是否含有s,有返回位置
if(iCharS!=str1.end())
str1.erase(iCharS);//删除 iCharS
cout<<str1<<endl;
//3.删除全部
str1 = "Good day String! Today is beautiful!";
//cout<<str1.erase(str1.begin(),str1.end())<<endl;
/*
字符串翻转 reverse
*/
reverse(str1.begin(),str1.end());
/*
大小写的转换
*/
cout<<"请输入一行字符串:"<<endl;
string strInput;
getline(cin,strInput);
//把字符串转换为大写
transform(strInput.begin(),strInput.end(),strInput.begin(),toupper);
//这句代码的意思是从 strInput.begin()开始到 strInput.end()结束, 转换为源数组的位置strInput.begin,转化为大写
transform(strInput.begin(),strInput.end(),strInput.begin(),tolower);
return 0;
}
string用法2
最新推荐文章于 2019-03-24 11:36:14 发布