C++字符串复习

前言

为了保证复习高效,以下不包括很简单的内容,例如cin。

C类型字符、字符串

输入方法

  • **char c = getchar()**输入单个字符

string类型字符串

输入方法

  • getline(cin, str) 整行输入

常用方法

  • s.substr(pos, len):截取字符串 spos 个位置开始,截取 len 个字符,并返回这个子字符串。

    1
    2
    string s = "Hello, World!";
    string sub = s.substr(7, 5); // "World"
  • s.insert(pos, str):在字符串 s 的第 pos 个位置之前,插入字符串 str,并返回修改后的字符串。

    1
    2
    string s = "Hello!";
    s.insert(5, ", World"); // "Hello, World!"
  • s.find(str, [pos]):在字符串 s 中,pos 个字符开始寻找子字符串 str,并返回其起始位置。如果找不到,则返回 string::npospos 可以省略,默认从位置 0 开始。

    1
    2
    string s = "Hello, World!";
    size_t pos = s.find("World"); // 7
  • s.replace(pos, len, str):在字符串 s 中,pos 个位置开始,替换 len 个字符为字符串 str,并返回修改后的字符串。

    1
    2
    string s = "Hello, World!";
    s.replace(7, 5, "Universe"); // "Hello, Universe!"
  • s.erase(pos, len):在字符串 s 中,pos 个位置开始,删除 len 个字符,并返回修改后的字符串。

    1
    2
    string s = "Hello, World!";
    s.erase(5, 7); // "Hello!"
  • **s.c_str()**:获取字符串 s 的C风格字符串指针(const char*),用于与C语言兼容的函数接口。

    1
    2
    string s = "Hello, World!";
    const char* cstr = s.c_str(); // "Hello, World!"