c++实现将输入的字符串首字母大写,字符串中的下划线替换成空格,并将后面的第一个字符变成大写

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 是指向容器元素的迭代器。
  • firstlast 分别表示要被替换的范围的起始和结束迭代器。
  • 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
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值