替换特定字母的函数不会以 void 返回类型运行

Function to replace specific letters won't run with void return type

本文关键字:void 返回类型 运行 函数 替换      更新时间:2023-10-16

我必须创建一个程序来替换第一个中的所有字母参数和第二个参数。例如,如果字符串传递的是"现在如何牛",该函数将所有"o"替换为"e"然后新字符串将是:"凿新cew。...我不断得到一个第 9 行错误,返回无效部分。

#include <iostream>
using namespace std;
string replace(string mystring){
    replace(mystring.begin(), mystring.end(),  'e',  'o');
    return void;
}

你只需要返回修改后的字符串,使用 return mystring; 而不是return void;<</p>

div class="answers">
string replace(string mystring){

此函数称为 replace,将字符串作为参数并返回一个字符串,在此原型中由函数名称前的类型指示。

如果它希望您返回字符串,则无法return void;因为 void 不是字符串类型。

因此,您需要改为return mystring;,以便返回一个字符串

与其返回 void,不如执行

replace(mystring.begin(), mystring.end(),  'e',  'o');
return mystring;

编辑:刚刚意识到我在谈论错误的语言。对不起大家。

不是

很优雅,但它会完成工作。 现在,您可以将字符串替换为其他字符串 - 或者只使用一个字符长的字符串(类似于您在示例中所做的)。

#include <iostream>
#include <cstdlib>
#include <string>
std::string string_replace_all( std::string & src, std::string const& target, std::string const& repl){
        if (target.length() == 0) {
                // searching for a match to the empty string will result in                                                                                                                                                                    
                //  an infinite loop                                                                                                                                                                                                           
                //  it might make sense to throw an exception for this case                                                                                                                                                                    
                return src;
        }
        if (src.length() == 0) {
                return src;  // nothing to match against                                                                                                                                                                                       
        }
        size_t idx = 0;
        for (;;) {
                idx = src.find( target, idx);
                if (idx == std::string::npos)  break;
                src.replace( idx, target.length(), repl);
                idx += repl.length();
        }
        return src;
}
int main(){
    std::string test{"loool lo l l l    l oooo l loo o"};
    std::cout << string_replace_all(test,"o","z") << std::endl;

    return EXIT_SUCCESS;
}

输出: lzzzl lz l l l zzzz l lzz z


如果要使用自己的实现,请小心并检查边缘情况。 确保程序不会在任何空字符串上崩溃。