#include <iostream>
using namespace std;
int main() {
/* 初始化 1 个 字符串(默认为空串, 即"") */
string s = "Hello World!";
/* 输入 1 个字符串 */
/* cin >> s; */
/* 输出 1 个字符串 */
cout << s << endl; /* Hello World! */
/* 通过索引访问 1 个字符串 */
for (int i = 0; i < s.length(); i++)
printf("%c", s[i]);
printf("\n");
/* Hello World! */
/* 将 C++ String 转化为 C 字符数组 */
printf("%s\n", s.c_str());
/* Hello World! */
/* insert() 常见用法 */
/* insert(pos, string) */
/* pos 表插入位置, string 表插入内容 */
cout << s << endl; /* Hello World! */
s.insert(0, "HDU, "); /* string 使用 C 字符串和 C++ 字符串都可以 */
cout << s << endl; /* HDU, Hello World! */
/* erase() 常见用法 */
/* erase(pos, length) */
/* pos 表删除起始位置, length 表删除字符个数 */
cout << s << endl; /* HDU, Hello World! */
s.erase(10, 6); /* 删除 " World" */
cout << s << endl; /* HDU, Hello! */
/* substr() 常见用法 */
/* substr(pos, len) */
/* pos 表起始位置, len表字符个数 */
/* 返回新串, 并非原处修改 */
cout << s << endl; /* HDU, Hello! */
cout << s.substr(5, 6) << endl; /* Hello! */
cout << s << endl; /* HDU, Hello! */
/* find() 常见用法 */
/* s.find(string) */
/* 返回 s 中第 1 次出现 string 的位置 */
/* 找不到则返回 string::npos */
/* string::npos 是 1 个特殊的数字, 找不到的标志, 常取 -1, 但本身用 unsigned 相关类型表示 */
cout << s << endl; /* HDU, Hello! */
string str = "ello";
cout << s.find("ello") << endl; /* 6 */
cout << s.find(str) << endl; /* 6 */
str = str + "1"; /* "ello1" */
if (s.find(str) == string::npos) {
printf("Not Found\n");
}
/* Not Found */
/* replace() */
/* replace(pos, len, string) */
/* 将从 pos 位开始, 长度为 len 的字串替换为 string */
/* 返回新串, 原处修改 */
cout << s << endl; /* HDU, Hello! */
cout << s.replace(5, 5, "World") << endl; /* HDU, World! */
cout << s << endl; /* HDU, World! */
return 0;
}
参考:フー・ファン・ゼン・レイ著『アルゴリズム・ノート』