#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
//字符串赋值
const char* constCstylestring = "Hello string";
string str1(constCstylestring);
string str2(str1);//*重要 本质是地址
string str4="HELLO WORLD";//*重要
string str3(10, 'a');
string str5(constCstylestring, 1);
cout << "Constant string is: " << constCstylestring << endl;
cout << "str1 string is " << str1 << endl;
cout << "str2 string is " << str2 << endl;
cout << "str6 string is " << str4 << endl;
// 字符串连接
str3 += str2;
str3.append(str5);
cout << "str3: " << str2 << endl;
cout << "str3: " << str3 << endl;
cout << "str5:" << str5 << endl;
//字符串的访问
for (int charcount = 0; charcount < str2.length(); charcount++)
cout << str2[charcount]<<endl;
int i = 0;
for (auto charlocate = str2.begin(); charlocate != str2.cend(); charlocate++)
cout << "charlocate[" << i++ << "] is "<< *charlocate<<endl ;
//字符串查找 1查找第一个 2查找所有
size_t charpos = str1.find("l", 0);
if (charpos == string::npos)
cout << "Not find";
else
cout << "First instance \"l\"at postion " << charpos<<endl;
charpos = str1.find("l", 0);
if (charpos == string::npos)
cout << "Not find";
else
while (charpos != string::npos)
{
cout << "First instance \"l\"at postion " << charpos << endl;
size_t searchoffset = charpos + 1;
charpos = str1.find("l", searchoffset);
}
//字符串的反转
reverse(str3.begin(), str3.end());
cout << str3 << endl;
//字符串删除
str1.erase(0, 1);
string::iterator ichar = find(str1.begin(), str1.end(), 'l');//注意不能是双引号
if (ichar != str1.end() )
{
str1.erase(ichar);
}
cout << str1<<endl;
string str("This is an example phrase."); string::iterator it;
cout << *(str.end()-1) << endl;
// 第(1)种用法
str.erase (10,8); cout << str << endl; // "This is an phrase."
// 第(2)种用法
it=str.begin()+9; str.erase (it); cout << str << endl; // "This is a phrase."
// 第(3)种用法
str.erase (str.begin()+5, str.end()-7); cout << str << endl; // "This phrase."
//大小写转换
str1=constCstylestring;
transform(str1.begin(), str1.end(), str1.begin(), ::toupper);
cout << str1<<endl;
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
cout << str1 << endl;
system("pause");
}
C++string1
最新推荐文章于 2025-03-26 15:05:35 发布