c++实现将输入的字符串首字母大写,字符串中的下划线替换成空格,并将后面的第一个字符变成大写
这个基本功能不难,可能很多同学会对字母变成大写有些迷茫,可能会使用ASCII值来进行转换。不要迷茫,这里介绍一个C 库函数 int toupper(int c)
把小写字母转换为大写字母。我们有了这个函数,这个功能就容易多了
#include <algorithm>
#include <cctype>
#include <iostream>
std::string convertString(const std::string &input) {
std::string output = input;
// 将第一个字符转换为大写
if (!output.empty()) {
output[0] = toupper(output[0]);
}
// 遍历字符串,将下划线替换为空格,并将后面的第一个字符转换为大写
for (size_t i = 1; i < output.length(); ++i) {
if (output[i] == '_') {
// 检查下划线后面是否有字符
if (i + 1 < output.length()) {
output[i] = ' ';
output[i + 1] = toupper(output[i + 1]);
} else {
// 移除末尾的下划线
output.erase(i);
--i; // 调整迭代器
}
}
}
return output;
}
int main() {
std::string input = "hello_world";
std::string result = convertString(input);
std::cout << "Converted string: " << result << std::endl;
return 0;
}
输出结果:
Converted string: Hello World
还可以使用std::replace
函数快速替换。函数原型如下:
template <class ForwardIterator, class T>
void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value);
其中:
ForwardIterator
是指向容器元素的迭代器。first
和last
分别表示要被替换的范围的起始和结束迭代器。old_value
是要被替换的旧值。new_value
是新值,将用来替换所有出现的old_value
。
同时还可以使int isalpha(int c);
函数检查给定字符是否是字母。
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
// 函数定义
std::string capitalizeAndReplace(std::string &str) {
std::string output = str;
// 使用std::replace将下划线替换为空格
std::replace(output.begin(), output.end(), '_', ' ');
bool capitalizeNext = true;
for (char &c : output) {
if (capitalizeNext && isalpha(c)) {
// 如果第一个是字母实现字符串首字母大写
c = toupper(c);
capitalizeNext = false;
} else if (c == ' ') { // 空格后面首字母大写
capitalizeNext = true;
}
}
return output;
}
int main() {
std::string input{"hello_world_123_haha"};
std::string output = capitalizeAndReplace(input);
std::cout << "Converted string: " << output << std::endl;
return 0;
}
输出结果:
Converted string: Hello World 123 Haha