C++STL之string

1.介绍

        在C++中,string是标准库中的一个类,用于处理字符串。相比于 C 风格字符串(字符数组),string提供了更强大和便捷的功能。

2.string用法

        (1)声明与初始化

std::string str; // 空字符串

std::string str = "Hello, World!";

std::string str1 = "Hello";
std::string str2(str1); // 使用 str1 初始化 str2

std::string str = "Hello, World!";
std::string subStr(str, 0, 5); // 从 str 的第 0 个字符开始,取 5 个字符,结果为 "Hello"

std::string str(5, 'a'); // 结果为 "aaaaa"

           (2)字符串操作

//获取长度
std::string str = "Hello";
int length = str.size(); // 或者 str.length(),结果为 5

//访问字符
std::string str = "Hello";
char ch = str[0]; // 访问第一个字符,结果为 'H'
char ch2 = str.at(1); // 访问第二个字符,结果为 'e'

//修改字符串
std::string str = "Hello";
str[0] = 'h'; // 修改第一个字符,结果为 "hello"
str += " World!"; // 追加字符串,结果为 "hello World!"

//比较字符串
std::string str1 = "Hello";
std::string str2 = "World";
if (str1 == str2) {
    std::cout << "Strings are equal" << std::endl;
} else {
    std::cout << "Strings are not equal" << std::endl;
}

//查找子字符串
std::string str = "Hello, World!";
size_t pos = str.find("World"); // 查找 "World" 的位置,结果为 7
if (pos != std::string::npos) {
    std::cout << "Found at position: " << pos << std::endl;
} else {
    std::cout << "Not found" << std::endl;
}

//提取子字符串
std::string str = "Hello, World!";
std::string subStr = str.substr(7, 5); // 从第 7 个字符开始,取 5 个字符,结果为 "World"

//插入字符串
std::string str = "Hello!";
str.insert(5, " World"); // 在第 5 个位置插入 " World",结果为 "Hello World!"

//删除字符串
std::string str = "Hello, World!";
str.erase(5, 7); // 从第 5 个字符开始,删除 7 个字符,结果为 "Hello!"

        (3)字符串与数值的转换

//字符转数值
std::string str = "123";
int num = std::stoi(str); // 字符串转整数
double d = std::stod("3.14"); // 字符串转浮点数

//数值转字符
int num = 123;
std::string str = std::to_string(num); // 整数转字符串
double d = 3.14;
std::string str2 = std::to_string(d); // 浮点数转字符串

         (4)遍历字符串

std::string str = "Hello";
for (char ch : str) {
    std::cout << ch << " ";
}
// 输出: H e l l o

        (5)清空字符串

std::string str = "Hello";
str.clear(); // 清空字符串,str 变为空字符串

        (6)检查字符串是否为空

std::string str = "Hello";
if (str.empty()) {
    std::cout << "String is empty" << std::endl;
} else {
    std::cout << "String is not empty" << std::endl;
}

        (7)与C风格字符串的转换

//string转C风格字符串
std::string str = "Hello";
const char* cstr = str.c_str(); // 返回 C 风格字符串(以 '\0' 结尾)

//C风格字符串转string
const char* cstr = "Hello";
std::string str(cstr); // 直接初始化

3.总结

      string提供了丰富的功能来操作字符串,包括初始化、修改、查找、比较、转换等。它是 C++ 中处理字符串的首选方式,并避免了 C 风格字符串的许多问题(如内存管理)。

如有错误,敬请指正!!!

你可能感兴趣的:(C++之STL容器,c++,开发语言)