替换特定字母的函数不会以 void 返回类型运行
Function to replace specific letters won't run with void return type
我必须创建一个程序来替换第一个中的所有字母参数和第二个参数。例如,如果字符串传递的是"现在如何牛",该函数将所有"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>
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
如果要使用自己的实现,请小心并检查边缘情况。 确保程序不会在任何空字符串上崩溃。
相关文章:
- 奇怪的结构&GCC&clang(void*返回类型)
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- 将返回类型专用化为 void 或 const 左值引用
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何在C++中将阿克曼函数更改为 void 返回类型
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 使用SFINAE来检测void返回类型函数的存在
- 具有非 void 返回类型的虚函数
- C++重写 void 函数返回类型会导致生成失败
- 替换特定字母的函数不会以 void 返回类型运行
- Constexpr类模板成员函数是否具有推导的void返回类型
- C void*任何类型实现都会返回奇怪的结果
- std::函数,返回类型为void,参数为模板化
- 从返回类型的函数中获取结果'void'而结果变量是输入参数之一 - C++
- 不返回值,来自具有非void返回类型的函数
- 如何确定作为void *返回的指针的类型(Class)
- 对链表c++中的未知返回类型使用void指针
- 是否可以检查函数是否具有 void 返回类型
- Android c++上的Qt与Java的互操作性在SIGSEGV为void或基本返回类型时失败