字符串函数第 2 部分
本课属于 Coddy C++ 学习旅程的“基础知识”单元。第 71 课,共 74 课。
下面还有一些处理字符串的实用函数:
- erase(pos, len):从当前字符串中删除从位置 pos 开始的 len 个字符。
- find(str):返回 str 在当前字符串中第一次出现的位置。如果未找到,则返回某个可以与 -1 比较的对象。
- clear():从字符串中移除所有字符,使其变为空。
- empty():如果字符串为空,则返回 true;否则返回 false。
例如,使用以下字符串:
std::string str = "Hello, World!";int pos = str.find("World");
// 输出:pos = 7("World" 开始的位置)str.erase(5, 2);
// 输出:“HelloWorld!”str.clear();
// 输出:""(空字符串)bool isEmpty = str.empty();
// 如果 str 中没有字符,就返回 true挑战
简单创建一个名为 stringSearchOperations 的函数,接收一个字符串作为输入,并使用字符串函数执行以下操作:
- 查找并打印字符串中第一个空格字符的位置。
- 从位置 5 开始删除 4 个字符。
- 检查字符串是否包含单词 "You",并打印 "Found" 或 "Not Found"。
- 清空字符串并检查它是否为空。
- 每次操作后打印结果。
使用以下格式:
Space Found At: [Position of space]
After Erase: [String after erasing]
Contains You: [Found/Not Found]
Is Empty: [true/false]亲手试试
#include <iostream>
#include <string>
void stringSearchOperations(std::string str) {
// 查找第一个空格
// 从位置 5 开始删除 4 个字符
// 检查是否包含 "You"
// 清空字符串并检查是否为空
}
int main() {
std::string str;
std::getline(std::cin, str);
stringSearchOperations(str);
return 0;
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: C++ 在线编译器