跳转到内容

C++ 字符串基础

来自代码酷

C++字符串基础[编辑 | 编辑源代码]

C++字符串是C++编程语言中用于存储和操作文本数据的基本数据类型。与C风格的字符数组不同,C++提供了更高级的std::string类(定义在<string>头文件中),具有丰富的成员函数和操作符重载,使字符串处理更加安全和便捷。

字符串类型概述[编辑 | 编辑源代码]

C++中有两种主要的字符串表示方式:

  • C风格字符串:以空字符('\0')结尾的字符数组
  • std::string:C++标准库提供的字符串类

C风格字符串[编辑 | 编辑源代码]

传统C风格的字符串实际上是字符数组,以空字符('\0')作为结束标志。

char cstr[] = "Hello";  // 自动添加'\0'

std::string[编辑 | 编辑源代码]

现代C++推荐使用std::string,它自动管理内存,并提供丰富的操作接口。

#include <string>
std::string str = "Hello World";

字符串声明与初始化[编辑 | 编辑源代码]

std::string有多种初始化方式:

std::string s1;              // 空字符串
std::string s2("Hello");     // 从C风格字符串初始化
std::string s3(5, 'a');      // 5个'a'字符
std::string s4 = "C++";      // 赋值初始化
std::string s5(s2);          // 拷贝构造

基本操作[编辑 | 编辑源代码]

字符串连接[编辑 | 编辑源代码]

使用+运算符或append()方法连接字符串:

std::string s1 = "Hello";
std::string s2 = "World";
std::string s3 = s1 + " " + s2;  // "Hello World"
s1.append(s2);                   // s1变为"HelloWorld"

字符串比较[编辑 | 编辑源代码]

可以直接使用比较运算符:

std::string a = "apple";
std::string b = "banana";
if (a < b) {  // 按字典序比较
    std::cout << a << " comes before " << b;
}

访问字符[编辑 | 编辑源代码]

使用[]运算符或at()方法访问特定位置的字符:

std::string str = "C++";
char c1 = str[0];   // 'C'
char c2 = str.at(1); // '+'

常用成员函数[编辑 | 编辑源代码]

函数 描述 示例
length()/size() 返回字符串长度 str.length()
empty() 检查是否为空字符串 str.empty()
clear() 清空字符串 str.clear()
substr(pos, len) 获取子串 str.substr(1, 2)
find(str) 查找子串位置 str.find("World")
replace(pos, len, str) 替换子串 str.replace(0, 5, "Hi")

字符串输入输出[编辑 | 编辑源代码]

从控制台读取[编辑 | 编辑源代码]

使用getline()读取整行:

std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);

输出到控制台[编辑 | 编辑源代码]

直接使用cout输出:

std::string msg = "Hello!";
std::cout << msg << std::endl;

字符串与数值转换[编辑 | 编辑源代码]

C++11引入了方便的转换函数:

// 字符串转数值
int i = std::stoi("42");
double d = std::stod("3.14");

// 数值转字符串
std::string s = std::to_string(123);

性能考虑[编辑 | 编辑源代码]

字符串操作可能涉及内存分配和复制。对于频繁拼接操作,可以使用ostringstream或reserve()预分配空间:

#include <sstream>
std::ostringstream oss;
oss << "The answer is " << 42;
std::string result = oss.str();

// 或者预分配
std::string bigStr;
bigStr.reserve(1000);  // 预分配1000字节

实际应用案例[编辑 | 编辑源代码]

用户输入验证[编辑 | 编辑源代码]

bool isValidUsername(const std::string& username) {
    if (username.empty() || username.length() > 20) {
        return false;
    }
    // 检查是否只包含字母和数字
    return username.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") == std::string::npos;
}

文本处理[编辑 | 编辑源代码]

std::string toUpper(std::string str) {
    for (char &c : str) {
        c = toupper(c);
    }
    return str;
}

字符串内存模型[编辑 | 编辑源代码]

graph LR A[std::string对象] --> B[数据指针] B --> C[堆内存] A --> D[大小] A --> E[容量]

总结[编辑 | 编辑源代码]

std::string提供了比C风格字符串更安全、更方便的文本操作方式。它自动管理内存,提供了丰富的成员函数,是现代C++程序中处理文本的首选方式。初学者应优先学习std::string的使用,只有在特定需要时才考虑使用C风格字符串。