以下是使用 C++ 实现以上题目的代码:\n\ncpp\n#include \<iostream\>\n#include \<string\>\nusing namespace std;\n\nint main() {\n string str;\n cout \<\< "请输入一个长度小于等于 40 的字符串:";\n getline(cin, str);\n\n string command;\n cout \<\< "请输入编辑命令(D/I/R):";\n cin \>\> command;\n\n if (command == "D") {\n char c;\n cout \<\< "请输入要删除的字符:";\n cin \>\> c;\n\n size_t pos = str.find(c);\n if (pos != string::npos) {\n str.erase(pos, 1);\n cout \<\< "删除后的字符串为:" \<\< str \<\< endl;\n } else {\n cout \<\< "not exist" \<\< endl;\n }\n } else if (command == "I") {\n char c1, c2;\n cout \<\< "请输入要插入的字符和指定字符:";\n cin \>\> c1 \>\> c2;\n\n size_t pos = str.find_last_of(c1);\n if (pos != string::npos) {\n str.insert(pos, 1, c2);\n cout \<\< "插入后的字符串为:" \<\< str \<\< endl;\n } else {\n cout \<\< "not exist" \<\< endl;\n }\n } else if (command == "R") {\n char c1, c2;\n cout \<\< "请输入要替换的字符和替换字符:";\n cin \>\> c1 \>\> c2;\n\n size_t pos = str.find(c1);\n while (pos != string::npos) {\n str[pos] = c2;\n pos = str.find(c1, pos + 1);\n }\n cout \<\< "替换后的字符串为:" \<\< str \<\< endl;\n } else {\n cout \<\< "无效的命令" \<\< endl;\n }\n\n return 0;\n}\n\n\n请按照提示输入字符串和编辑命令,程序将输出对应的结果或提示信息。

C++ 字符串编辑:删除、插入、替换

原文地址: https://www.cveoy.top/t/topic/pTmw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录