string是一个char*型的容器,相当于C++风格的字符串。char*是一个指针,而string的本质是一个类
/*
* 版权所有 公众号 VxWorks567
*/
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
int testStr()
{
const char *chars1 = "ccc";
char chars2[] = "ddd";
string str1;
string str2;
// 使用字符常量初始化string
str1 = chars1;
// 使用字符数组初始化string
str2 = chars2;
string str = "Hello World";
// cout直接输出string的字符
cout << "cout: " << str << endl;
// c_str()将string 转换为 char*
const char *chars = str.c_str();
printf("printf: %s\n", chars);
// empty()判断string是否为空
cout << "empty: " << str.empty() << endl;
// compare()判断两个string是否相同
cout << "compare: " << str.compare("Hello Worl") << endl;
cout << "compare: " << str.compare("Hello World") << endl;
cout << "compare: " << str.compare("Hello Worldd") << endl;
// length()/size()计算string的字符数量
cout << "length: " << str.length() << endl;
// max_size()返回string的字符容量
cout << "max_size: " << hex << str.max_size() << endl;
// resize()调整string的长度, 变长则追加, 变短则截取
str.resize(str.size()+2, 'x');
cout << "resize: " << str << endl;
// push_back()表示追加1个字符
str.push_back('y');
cout << "push_back: " << str << endl;
// append()表示追加string或多个字符
cout << "append: " << str.append(str1) << endl;
cout << "append: " << str.append(2, 'a') << endl;
// replace()表示替换
cout << "replace: " << str.replace(str.size()-2, 2, "zz") << endl;
// insert()表示插入
str.insert(str.size()-2, "ww");
cout << "insert: " << str << endl;
// erase()表示删除
cout << "erase: " << str.erase(str.size()-5, 5) << endl;
// find()在string中查找子串出现的位置
cout << "find: " << str.find("llo") << endl;
// 子串不存在就返回npos, 值为0xffffffff
cout << "find: " << hex << str.find("lmn") << endl;
// rfind()在string中由右向左查找子串出现的位置
cout << "rfind: " << dec << str.rfind("l") << endl;
// find_first_of()在string中查找子串中的任意字符第一次出现的位置
cout << "find_first_of: " << str.find_first_of("lmn") << endl;
// find_last_of()在string中查找子串中的任意字符最后一次出现的位置
cout << "find_last_of: " << str.find_last_of("lmn") << endl;
// find_first_not_of()在string中查找第一个不同于子串任意字符的字符位置
cout << "find_first_not_of: " << str.find_first_not_of("lmn") << endl;
// find_last_not_of()在string中查找最后一个不同于子串任意字符的字符位置
cout << "find_last_not_of: " << str.find_last_not_of("lmn") << endl;
// substr()返回string的子串
cout << "substr: " << str.substr(1, 4) << endl;
// swap()交换string
cout << "before swap: " << str << " " << str1 << endl;
str.swap(str1);
cout << "after swap: " << str << " " << str1 << endl;
// assign()表示赋值
cout << "assign: " << str.assign(str2) << endl;
// +表示连接
cout << "+: " << str+str1 << endl;
// []表示取成员
cout << "[]: " << str[1] << endl;
// clear()表示清空
str.clear();
cout << "clear: " << str << endl;
return 0;
}