使用string和string_view(四)——练习
目录
- 1. 练习2.1
- 题目
- 答案
- 2. 练习2.2
- 题目
- 答案
- 3. 练习2.3
- 题目
- 答案
- 参考
1. 练习2.1
题目
编写一个程序,要求用户输入两个字符串,然后使用三向比较运算符将其按字母表顺序打印出来。为了获取一个字符串,可以使用std::cin流。
std::string s;
std::getline(std::cin, s);
答案
int main() {
std::string s1, s2;
std::cout << "input String1: ";
std::getline(std::cin, s1);
std::cout << "input String2: ";
std::getline(std::cin, s2);
std::strong_ordering result = s1 <=> s2;
if (std::is_lt(result)) {
std::cout << std::format("{}\n{}\n", s1, s2);
}
else if (std::is_gt(result)) {
std::cout << std::format("{}\n{}\n", s2, s1);
}
else {
std::cout << std::format("{}\n{}\n", s1, s2);
}
}
2. 练习2.2
题目
编写一个程序,要求用户提供源字符串haystack、要在源字符串中查找的字符串needle以及替换字符串。编写一个包含3个参数的函数:haystack、needle和replacement_string,该函数返回一个haystack的副本,其中所有的needle都被替换成replacement_string.要求使用std::string,不使用std::string。你将使用哪种类型的参数,为什么?在main()中调用此函数并打印所有字符串以进行验证。
答案
static std::string replaceAllSubString(
const std::string& haystack,
const std::string& needle,
const std::string& replacement_string) {
std::string newstr { haystack };
size_t pos { newstr.find(needle) };
while (pos != std::string::npos) {
newstr = newstr.erase(pos, needle.size());
newstr = newstr.insert(pos, replacement_string);
pos = newstr.find(needle, pos + replacement_string.size());
}
return newstr;
}
int main() {
std::string s { "ababbbbbaaababababababababbaaaaa" };
std::string olds { "ab" };
std::string news { "aba" };
std::cout << replaceAllSubString(s, olds, news) << std::endl;
}
3. 练习2.3
题目
修改练习2.2中的程序,并尽可能多地使用std::string_view。
答案
static std::string replaceAllSubString(
std::string_view haystack,
std::string_view needle,
std::string_view replacement_string) {
std::string newstr { haystack };
size_t pos { newstr.find(needle) };
while (pos != std::string::npos) {
newstr = newstr.erase(pos, needle.size());
newstr = newstr.insert(pos, replacement_string);
pos = newstr.find(needle, pos + replacement_string.size());
}
return newstr;
}
int main() {
std::string_view s { "ababbbbbaaababababababababbaaaaa" };
std::string_view olds { "ab" };
std::string_view news { "aba" };
std::cout << replaceAllSubString(s, olds, news) << std::endl;
}
参考
[比] 马克·格雷戈勒著 程序喵大人 惠惠 墨梵 译 C++20高级编程(第五版)