
string是C++、java、VB等编程语言中的字符串,字符串是一个特殊的对象,属于引用类型。 在java、C#中,String类对象创建后, 字符串一旦初始化就不能更改,因为string类中所有字符串都是常量,数据是无法更改,由于string对象的不可变,所以可以共享。对String类的任何改变,都是返回一个新的String类对象。 C++标准库中string类以类型的形式对字符串进行封装,且包含了字符序列的处理操作。

#include
using namespace std;
#include
int main()
{
string s1 = "abc"; //双引号
string s2("def"); // 双引号
string s3(3, 'c'); //左边是字符的数量,右边是字符 单引号
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
cout << "s3:" << s3 << endl;
return 0;
}

#include
using namespace std;
#include
int main()
{
char sz[] = "abcd";
string s1 = "nihaoa";
string s4(sz); // 对char字符串进行复制
string s2(s1); // 对string 复制
cout << s4 << endl;
cout << s2 << endl;
return 0;
}

#include
using namespace std;
#include
int main()
{
string s = "abcd";
const char* p = s.c_str(); //c_str();
cout << "string字符串转换为char字符串:" <<p<< endl;
return 0;
}

assign(数组,几位开始,取几个函数)
#include
using namespace std;
#include
int main()
{
string s1;
s1.assign("aaaaaaaaaa"); // 输出这些字符串
cout << s1 << endl;
const char* p = "abcd";
string s2;
s2.assign(p); // 不输入,就是字符串的全部
cout << s2 << endl;
string s3;
s3.assign(p, 3); // 字符串的前三个
cout << s3 << endl;
string s6;
s6.assign(p, 0, 3); // 打印字符串从第1个元素开始,打印三个.
cout << s6 << endl;
return 0;
}

#include
using namespace std;
#include
int main()
{
string s = "abcd";
if (s.empty())
{
cout << "该字符串为空" << endl;
}
else
{
cout << "该字符串不为空" << endl;
}
return 0;
}

#include
using namespace std;
#include
int main()
{
string s = "abcd";
s.clear(); // 对字符串进行清空处理
if (s.empty())
{
cout << "该字符串为空" << endl;
}
else
{
cout << "该字符串不为空" << endl;
}
return 0;
}

#include
using namespace std;
#include
int main()
{
string s1 = "hello";
s1.at(0); // at()函数
cout << "字符串s1的地1个是多少:" << s1.at(0) << endl;
return 0;
}


从第几个元素开始,往后数几个元素。
查找哪个元素或字符串,从第几个开始。
从第几个开始,往后数几个,换成谁。
从第几个开始,插入谁。
从第几个开始,插入几个,插入谁。
从第几个开始,删除几个。
#include
#include
using namespace std;
int main()
{
string s1,s2,s4,s5,s6,s7,s8;
int s3;
s1 = "hello cctv.com byebye";
cout << "原数组为:" << s1 << endl;
s2=s1.substr(6, 8); // 从第几个开始,进行提取几个,
cout <<"通过数数得:"<< s2 << endl;
s3 = s1.find("cctv.com",0); // 找谁, 从第几个元素找
s4 = s1.substr(s3, 8);
cout <<"通过找到得:"<< s4 << endl;
s5 = s1.replace(0, 5, "李威涛"); //从第几个开始,前几个字符换成后面的
cout << "通过replace进行添加:" << s5 << endl;
s6 = s1.insert(0, "勇敢的"); //第几个开始 ,插入谁
cout << "通过插入进行添加:" << s6 << endl;
s7 = s1.insert(0, 3, 'v'); // 第几个开始,插入几个,插入谁
cout << "插入字符为:" << s7 << endl;
s1 = s1 + " 888";
cout << s1 << endl;
s8 = s1.erase(0, 5); //第几个开始, 删除几个
cout << "删除:" << s8 << endl;
}


制作不易!!!! 还请支持…