我无法使用功能将字符串内的字符加倍 [英] I can't double characters inside string with function

查看:105
本文介绍了我无法使用功能将字符串内的字符加倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的函数,该函数将字符串内的字符加倍并输出新的字符串.前任. "hello world"会变成"hheelloo wwoorrlldd"但是,使用我编写的函数,输出为空.如果有人能告诉我这是为什么,我将不胜感激.谢谢!

I am trying to create a simple function that double the characters inside of a string and outputs the new string. Ex. "hello world" would become "hheelloo wwoorrlldd" However, with the function I wrote, the output is empty. If anyone can tell me why this is, I'd greatly appreciate it. Thank you!

using namespace std;
string doubleChar(string str) {
    string newString;
    for(int i =0;i<str.size();++i){
        newString[i] = str[i];
        newString[i+1] = str[i];
    }
    return newString;
}

推荐答案

尽管songyuanyao的解决方案很好,但我认为可以使用更多的C ++函数...

Altough the solution by songyuanyao is nice, I think more C++ functions can be used...

#include <string>
#include <string_view>

// use string view, so a character array is also accepted
std::string DoubleChar(std::string_view const &str) noexcept {
    std::string newString;
    newString.reserve(str.size() * 2);
    for (auto character : str) { // use range based loop
        newString.append(2, character); // append the character twice
    }
    return newString;
}

#include <iostream>

int main() {
    std::string const str = "Hello world";

    std::cout << DoubleChar(str) << '\n';
}

这篇关于我无法使用功能将字符串内的字符加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆