C++ 字符串入门

教学定位

建议 90 分钟。目标是掌握 std::string 的读写、长度、下标、拼接、比较、查找和截取,理解 ASCII 转换,并能独立完成回文、字符统计和大小写转换。重点检查 cin/getline 混用、下标从 0 开始和越界问题。

第一部分:欢迎来到字符串的世界!

字符串(string),顾名思义,就是一“串”字符连接在一起。
比如你的名字 “ZhangSan”,一句诗 “Hello world”,都是字符串。在C++中,它是我们处理文本信息的最强有力的武器。

第二部分:选择你的“座驾”—— string vs char[]

特性std::string (智能汽车)char[] (手动挡老爷车)我们的选择
头文件#include <string>无需
声明string s = "hello";char s[] = "hello";
内存管理自动,无需担心长度手动,需要预估最大长度,容易溢出std::string
功能极其丰富,自带各种方便的函数基础,依赖<cstring>库函数
安全性低,容易出错

结论: 在信息学竞赛中,请始终优先使用 string`

第三部分:std::string 的神奇工具箱(核心操作详解)

1. 声明与读写

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    // 声明
    string s1; // 一个空字符串
    string s2 = "hello"; // 初始化为 "hello"
 
    // 读入
    string word, line;
    cout << "请输入一个单词: ";
    cin >> word; // 只会读取到第一个空格前
    cout << "你输入的单词是: " << word << endl;
 
    // !! 注意:cin 之后立刻用 getline,需要清除缓冲区 或者 
    cin.ignore(); 
 
    cout << "请输入一句话: ";
    getline(cin, line); // 读取一整行
    cout << "你输入的话是: " << line << endl;
 
    return 0;
}

⚠️注意: cin >> 会将换行符留在输入流中,如果紧接着使用 getline,它会立刻读到这个换行符并结束。解决方法是在两者之间加一句 cin.ignore();。详见 cin 输入机制讲解

2. 访问长度与单个字符

string s = "Olympiad";
// 获取长度
cout << "长度是: " << s.size() << endl; // 输出 8 
cout << "长度是: " << s.length() << endl;
 
// 访问单个字符 (下标从0开始)
cout << "第一个字符: " << s[0] << endl; // 输出 'O'
cout << "最后一个字符: " << s[s.size() - 1] << endl; // 输出 'd'

3. 拼接与比较

string s1 = "apple";
string s2 = "pie";
// 拼接
string s3 = s1 + s2; // s3 变为 "applepie"
 
// 比较 (按字典序)
if (s1 < "banana") {
    cout << "apple is smaller than banana" << endl;
}

4. 常用函数

函数功能示例 string s = "I love C++";说明
s.substr(pos, len)截取从下标pos开始,长度为len的子串s.substr(2, 4) 结果是 "love"截取范围是 [pos, pos + len)
s.find(pattern)查找pattern首次出现的位置s.find("C++") 结果是 7
s.insert(pos, str)在下标pos处插入strs.insert(1, " really") 结果是 "I really love C++"
s.erase(pos, len)从下标pos处删除len个字符s.erase(0, 2) 结果是 "love C++"
s.push_back(char)在字符串末尾添加一个字符s.push_back('!'); 结果是 "I love C++!"cout<<s;
** 5.借助AI学习编程,string的用法 **

第四部分:字符的秘密——ASCII码

计算机中,每个字符都对应一个唯一的数字,这张对应表就叫ASCII码。

  • 'A''Z' 是连续的 (65 … 90)
  • 'a''z' 是连续的 (97 … 122)
  • '0''9' 是连续的 (48 … 57)

    应用实例:
// 1. 小写转大写
char lower = 'c';
char upper = lower - 32; // 或者 lower - 'a' + 'A'
// upper 现在是 'C'
 
// 2. 数字字符转整数
char digit_char = '7';
int number = digit_char - '0';
// number 现在是 7

第五部分:实战演练——回文串判断

题目: 判断一个字符串是否是回文串。
思路: 使用双指针,一个从头开始(i),一个从尾开始(j),向中间移动。如果s[i]s[j]始终相等,则是回文串。
参考代码:

#include <iostream>
#include <string>
#include <algorithm> // 包含 reverse 函数
 
using namespace std;
 
// 方法一:双指针法
bool isPalindrome_1(string s) {
    int len = s.size();
    for (int i = 0; i < len / 2; i++) {
        if (s[i] != s[len - 1 - i]) {
            return false;
        }
    }
    return true;
}
 
int main() {
    string s;
    cin >> s;
    if (isPalindrome_1(s)) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
    return 0;
}

第六部分:习题

https://www.luogu.com.cn/problem/B2109
https://www.luogu.com.cn/problem/B2113
https://www.luogu.com.cn/problem/B2112
https://www.luogu.com.cn/problem/B2114

https://www.luogu.com.cn/problem/B2110 [讲解?]
https://www.luogu.com.cn/problem/B2116 [讲解?]

今日总结:

  • std::string 是我们的好朋友,功能强大又安全。
  • cin 读单词,getline 读句子。
  • 下标从 0 开始,长度是 .size()
  • 字符可以像数字一样加加减减(ASCII码)。
    string-data-sheet
    现在,打开你的IDE,开始你的字符串探险之旅吧!
    进阶:stringstream