Menu
CoddyTech

字符串函数第 1 部分

本课属于 Coddy C++ 学习旅程的“基础知识”单元。第 70 课,共 74 课。

下面是字符串中一些实用的函数:

  • insert(pos, str):在当前字符串的 pos 位置插入字符串 str。
  • replace(pos, len, str):将从位置 pos 开始的 len 个字符替换为字符串 str。
  • substr(pos, len):返回当前字符串的一个子字符串,从位置 pos 开始,长度为 len。
  • append(str):将字符串 str 添加到当前字符串的末尾。

例如,使用以下字符串:

std::string str = "Hello, World!";
str.insert(5, " C++");
// 输出:“Hello C++, World!”
str.replace(7, 5, "Universe");
// 输出:“Hello, Universe!”
str.substr(0, 5);
// 输出:“Hello”
str.substr(7, 5);
// 输出:“World”
str.substr(7);
// 输出:“World!”
str.append(" This is universe");
// 输出:"Hello, World! This is universe"
challenge icon

挑战

简单

创建一个名为 stringOperations 的函数,它接收一个字符串作为输入,并使用字符串函数执行以下操作:

  1. 打印字符串的长度。
  2. 将字符串 " - Modified" 追加到原始字符串。
  3. 在字符串开头插入字符串 "C++ "。
  4. 提取从位置 5 开始、长度为 5 的子字符串。
  5. 将从位置 5 开始、长度为 5 的子字符串替换为字符串 "Awesome"。
  6. 每次操作后打印修改后的字符串。

使用以下格式:

Length: [Length of string]
Append: [After Appending]
Insert: [After Insert]
Extract: [The extracted string]
Replace: [After replacing]

亲手试试

#include <iostream>
#include <string>

void stringOperations(std::string str) {
    // 1. 输出字符串的长度

    // 2. 在字符串末尾追加 " - Modified"

    // 3. 在开头插入 "C++ "

    // 4. 从位置 5 开始提取长度为 5 的子字符串

    // 5. 将位置 5 处的子字符串替换为 "Awesome"
    
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    stringOperations(str);
    return 0;
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: C++ 在线编译器