#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include "string"
#include "algorithm"
void main21()
{
string s1 = "aaaa";
string s2("bbbb");
string s3 = s2;
string s4 (10, 'a');
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
cout << "s3:" << s3 << endl;
cout << "s4:" << s4 << endl;
}
void main22()
{
string s1 = "asdfgh";
for (int i = 0; i < s1.length();i++)
{
cout << s1[i] << " ";
}
cout << endl;
for (string::iterator it = s1.begin(); it!= s1.end(); it++)
{
cout << *it<< " ";
}
cout << endl;
for (int i = 0; i < s1.length()+3; i++)
{
cout << s1.at(i) << " ";
}
cout << endl;
}
void main23()
{
string s1 = "aaabbbb";
//1 s1===>char *
printf("s1:%s \n", s1.c_str());
//2 char *====>sting
//3 s1的内容 copy buf中
char buf1[128] = {0};
s1.copy(buf1, 4, 3); //注意 只给你copy3个字符 不会变成C风格的字符串(没有\0)
cout << "buf1:" << buf1 << endl;
}
//复制
void main233()
{
string s1 = "aaaaa";
printf("s1:%s \n", s1.c_str());
char buf[128];
s1.copy(buf, 3, 0); //copy(字符串,大小,开始位)只复制3个 没有结束符号(没有\0)
cout << "buf: " << buf << endl;
}
//替换
void main24()
{
string s1 = "aaaaa";
string s2 = "bbbbb";
s1 = s1 + s2;
cout << "s1:" << s1 << endl;
s2.append(s1); //连接
cout << "s2:" << s2 << endl;
}
//查找、替换
void main25()
{
string s1 = "www aas aaa sss www 123 www 222";
int index = s1.find(" aas", 0);
cout << index << endl;
int offindex = s1.find("www", 0);
while (offindex != string::npos)
{
cout << "offindex:" << offindex << endl;
offindex++;
offindex = s1.find("www", offindex);
}
offindex = s1.find("www", 0);
while (offindex != string::npos)
{
cout << "offindex:" << offindex << endl;
s1.replace(offindex, 3, "WWW"); //替换(开始位,大小,替换为)
offindex++;
offindex = s1.find("www", offindex);
}
cout << "replace:" << s1 << endl;
}
//查找、插入、删除
void main26()
{
string s1 = "asdfghjkllkjhgfdsa";
cout << s1 << endl;
string::iterator it = find(s1.begin(), s1.end(), 'f');
while (it != s1.end())
{
s1.erase(it);
it = find(it, s1.end(), 'f');
}
cout << s1 << endl;
s1.insert(s1.length(), "aaa");//s1.length()后插入
cout << s1 << endl;
s1.erase(s1.begin(), s1.end());//整个删除
cout << s1 << endl;
}
//大小写转换
void main27()
{
string s1 = "aaaBBB";
transform(s1.begin(), s1.end(), s1.begin(), toupper);//大写
cout << s1 << endl;
transform(s1.begin(), s1.end(), s1.begin(), tolower);//小写
cout << s1 << endl;
}
void main()
{
main27();
cout<<"hello"<<endl;
system("pause");
return;
}
【C++备忘录】string用法(单个输出、复制、拼接、查找、替换、插入、删除、大小写转换)
最新推荐文章于 2022-03-11 21:23:17 发布