#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void test01() {
string string1; // 默认构造
string string2(string1); // copy构造
string string3 = string1;
string string4 = "abcd";
string string5(10, 'a');
// 基本赋值
string1 = "hello";
string2 = string4;
string3.assign("abcdef", 4);
string string6;
string6.assign(string1, 1, 3);
cout << string6 << endl;
}
void test02() {
string string1 = "hello world";
for (int i = 0; i < string1.size(); i++) {
//cout << string1[i] << endl;
cout << string1.at(i) << endl; // [] 和 at 的区别: 当访问越界时, []直接挂掉, at会抛出异常;
}
try {
string1.at(100);
}
catch(out_of_range &exception) {
cout << "out_of_range: " << exception.what() << endl;
}
catch(...) {
cout << "unknown error" << endl;
}
}
void test03() {
// 字符串拼接
string string1 = "I";
string string2 = (string1 += " love xuyushan");
cout << string2 << endl;
string2.append(" forever");
cout << string2 << endl;
}
void test04() {
// find 查找
string string1 = "abcdefg";
int position1 = string1.find("bcd"); // 从左开始找: 如果没有找到则返回 -1
cout << "position1 = " << position1 << endl;
int position2 = string1.rfind("bc");
cout << "position2 = " << position2 << endl; // 从右开始找: 如果没有找到则返回 -1
}
void test05() {
// replace 替换
string string2 = "hello";
string2.replace(1, 3, "111");
cout << string2 << endl;
}
void test06() {
string string1 = "abc";
string string2 = "abc";
if (string1.compare(string2) == 0) {
cout << "string1 == string2" << endl;
} else if (string1.compare(string2) == 1) {
cout << "string1 > string2" << endl;
} else if (string1.compare(string2) == -1) {
cout << "string1 < string2" << endl;
}
}
void test07() {
// 子串
string string1 = "abcde";
string string2 = string1.substr(1, 3);
//cout << string2 << endl;
string email = "234198652@qq.com";
int position = email.find("@");
cout << email.substr(0, position) << endl;
}
void test08() {
// 插入 删除
string string1 = "hello";
string1.insert(1, "111"); // 插入
cout << string1 << endl;
string1.erase(1, 3); // 删除
cout << string1 << endl;
}
void stringFunction(string someString) {
cout << someString << endl;
}
void test09() {
string string1 = "abc";
const char* p = string1.c_str();
stringFunction(p); // 隐式类型转换为 string
}
string& tocapitalize(string& tempString) {
for (int i = 0; i < tempString.size(); i++) {
if (i == 0) {
tempString[i] = toupper(tempString[i]);
continue;
}
tempString[i] = tolower(tempString[i]);
}
return tempString;
}
// 自定义字符串操作函数
void test10() {
string string1 = "abCdEfg";
tocapitalize(string1);
cout << string1 << endl;
}
int main() {
//test01();
//test02();
//test03();
//test04();
//test05();
//test06();
//test07();
//test08();
//test09();
test10();
return EXIT_SUCCESS;
}