C++字符串操作:翻转、首尾添加字符
C++字符串操作:翻转、首尾添加字符
本博客提供了一个C++程序,该程序可以对字符串进行一系列操作,包括:
- 翻转字符串
- 在字符串开头添加字符
- 在字符串末尾添加字符
以下是完整的C++代码:
#include <iostream>
#include <string>
#include <vector>
std::string modifyName(const std::string& name, const std::vector<std::pair<int, std::pair<int, char>>>& operations) {
std::string modifiedName = name;
for (const auto& operation : operations) {
int type = operation.first;
int flag = operation.second.first;
char ch = operation.second.second;
if (type == 1) {
std::reverse(modifiedName.begin(), modifiedName.end());
} else if (type == 2) {
if (flag == 1) {
modifiedName = ch + modifiedName;
} else if (flag == 2) {
modifiedName += ch;
}
}
}
return modifiedName;
}
int main() {
std::string name;
std::cin >> name;
int k;
std::cin >> k;
std::vector<std::pair<int, std::pair<int, char>>> operations(k);
for (int i = 0; i < k; i++) {
std::cin >> operations[i].first;
if (operations[i].first == 2) {
std::cin >> operations[i].second.first >> operations[i].second.second;
}
}
std::string modifiedName = modifyName(name, operations);
std::cout << modifiedName << std::endl;
return 0;
}
代码说明:
modifyName函数:- 接受一个字符串
name和一个操作列表operations作为输入。 - 遍历
operations列表,根据操作类型(type)和标志位(flag)对字符串进行修改。 - 返回修改后的字符串
modifiedName。
- 接受一个字符串
main函数:- 读取初始字符串
name和操作数量k。 - 读取
k个操作,并将操作参数存储在operations向量中。 - 调用
modifyName函数对字符串进行修改。 - 输出修改后的字符串。
- 读取初始字符串
使用方法:
- 输入初始字符串。
- 输入要执行的操作数量。
- 对于每个操作:
- 输入操作类型(1:翻转字符串,2:添加字符)。
- 如果操作类型为2,则输入标志位(1:在开头添加字符,2:在末尾添加字符)和要添加的字符。
示例:
输入:
hello
3
2 1 w
1
2 2 d
输出:
dlrowolleh
这段代码展示了如何使用C++进行基本的字符串操作。您可以根据需要修改和扩展这段代码,以实现更复杂的字符串处理功能。
原文地址: https://www.cveoy.top/t/topic/bkOH 著作权归作者所有。请勿转载和采集!