std::string` 类
以下是对 std::string
类中 修改操作 和 字符串操作 的示例代码,帮助你更好地理解这些函数的使用:
5. 修改操作
(1) operator+=
用于追加字符串、C 风格字符串或字符。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
str += ", World!"; // 追加 C 风格字符串
str += '!'; // 追加字符
std::cout << str << std::endl; // 输出: Hello, World!!
return 0;
}
(2) append()
用于追加字符串、C 风格字符串或字符序列。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
str.append(" World"); // 追加 C 风格字符串
str.append(3, '!'); // 追加 3 个 '!'
std::cout << str << std::endl; // 输出: Hello World!!!
return 0;
}
(3) push_back()
在字符串末尾添加一个字符。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
str.push_back('!');
std::cout << str << std::endl; // 输出: Hello!
return 0;
}
(4) insert()
在指定位置插入字符串。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
str.insert(5, ", C++"); // 在第 5 个位置插入 ", C++"
std::cout << str << std::endl; // 输出: Hello, C++ World
return 0;
}
(5) erase()
删除指定位置的字符或子串。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
str.erase(5, 2); // 从第 5 个位置删除 2 个字符
std::cout << str << std::endl; // 输出: Hello World!
return 0;
}
(6) replace()
替换指定位置的子串。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
str.replace(7, 5, "C++"); // 从第 7 个位置替换 5 个字符为 "C++"
std::cout << str << std::endl; // 输出: Hello, C++!
return 0;
}
(7) clear()
清空字符串。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
str.clear();
std::cout << "After clear: " << str << std::endl; // 输出: After clear:
return 0;
}
(8) swap()
交换两个字符串的内容。
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
str1.swap(str2);
std::cout << "str1: " << str1 << ", str2: " << str2 << std::endl; // 输出: str1: World, str2: Hello
return 0;
}
6. 字符串操作
(1) c_str()
返回一个指向 C 风格字符串的指针。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
const char* cstr = str.c_str();
std::cout << "C string: " << cstr << std::endl; // 输出: C string: Hello, World!
return 0;
}
(2) substr()
返回从指定位置开始的子串。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string sub = str.substr(7, 5); // 从第 7 个位置开始,取 5 个字符
std::cout << "Substring: " << sub << std::endl; // 输出: Substring: World
return 0;
}
(3) find()
查找子串第一次出现的位置。
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
size_t pos = str.find("World"); // 查找 "World" 的位置
if (pos != std::string::npos) {
std::cout << "Found 'World' at position: " << pos << std::endl; // 输出: Found 'World' at position: 7
} else {
std::cout << "Substring not found!" << std::endl;
}
return 0;
}
总结
这些操作是 std::string
类中最常用的功能,通过它们可以轻松实现字符串的修改和查找。希望这些示例能帮助你更好地理解和应用这些函数!