C++ string字符串基本操作

定义和初始化 string 对象

1. 默认初始化

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    cout << "Default initialized string: '" << str << "'" << endl;
    return 0;
}

运行结果:

Default initialized string: ''

2. 从 C 风格字符串初始化

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello";
    cout << "Initialized from C-style string: '" << str << "'" << endl;
    return 0;
}

运行结果:

Initialized from C-style string: 'Hello'

3. 复制初始化

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = str1;
    cout << "Copied string: '" << str2 << "'" << endl;
    return 0;
}

运行结果:

Copied string: 'Hello'

4. 部分复制

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = string("Hello World", 5);
    cout << "Partially copied string: '" << str << "'" << endl;
    return 0;
}

运行结果:

Partially copied string: 'Hello'

5. 重复字符

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str(5, 'a');
    cout << "String of repeated characters: '" << str << "'" << endl;
    return 0;
}

运行结果:

String of repeated characters: 'aaaaa'

string 对象上的操作

1. 添加

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello";
    str += " there";
    str.append("!");
    cout << "After append: '" << str << "'" << endl;
    return 0;
}

运行结果:

After append: 'Hello there!'

2. 插入

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello";
    str.insert(5, " World");
    cout << "After insert: '" << str << "'" << endl;
    return 0;
}

运行结果:

After insert: 'Hello World'

3. 查找

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    size_t pos = str.find("World");
    cout << "'World' found at position: " << pos << endl;
    return 0;
}

运行结果:

'World' found at position: 6

4. 替换

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    str.replace(6, 5, "there");
    cout << "After replace: '" << str << "'" << endl;
    return 0;
}

运行结果:

After replace: 'Hello there'

5. 获取子字符串

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    string sub = str.substr(0, 5);
    cout << "Substring: '" << sub << "'" << endl;
    return 0;
}

运行结果:

Substring: 'Hello'