C++STL 容器string 字符串操作
作者:野牛程序员:2023-12-27 14:18:55 C++阅读 2713
C++ STL中的string
容器提供了丰富的字符串操作功能,以下是一些常用的string
字符串操作示例:
创建字符串:
#include <iostream> #include <string> int main() { // 使用构造函数初始化字符串 std::string str1 = "Hello, "; std::string str2 = "world!"; // 使用加号连接两个字符串 std::string result = str1 + str2; std::cout << "Result: " << result << std::endl; return 0; }
获取字符串长度:
#include <iostream> #include <string> int main() { std::string str = "Hello, world!"; // 获取字符串长度 size_t length = str.length(); std::cout << "Length: " << length << std::endl; return 0; }
访问字符串中的字符:
#include <iostream> #include <string> int main() { std::string str = "Hello, world!"; // 访问字符串中的字符 char firstChar = str[0]; char lastChar = str[str.length() - 1]; std::cout << "First character: " << firstChar << std::endl; std::cout << "Last character: " << lastChar << std::endl; return 0; }
比较字符串:
#include <iostream> #include <string> int main() { std::string str1 = "apple"; std::string str2 = "orange"; // 比较字符串 if (str1 == str2) { std::cout << "Strings are equal." << std::endl; } else { std::cout << "Strings are not equal." << std::endl; } return 0; }
查找子串:
#include <iostream> #include <string> int main() { std::string str = "Hello, world!"; std::string substring = "world"; // 查找子串 size_t found = str.find(substring); if (found != std::string::npos) { std::cout << "Substring found at position: " << found << std::endl; } else { std::cout << "Substring not found." << std::endl; } return 0; }
这些示例演示了string
容器的一些常见操作,可以根据需要选择适合情况的操作。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
