gpt4 book ai didi

c++ - 大写字母

转载 作者:行者123 更新时间:2023-12-01 14:36:42 27 4
gpt4 key购买 nike

我遇到了一个小问题。我想利用字符串中的双字母。我设法编译了一个程序,但没有成功。

#include <iostream>
#include <cctype>
#include <string>

std::string::iterator function(
std::string::const_iterator a,
std::string::const_iterator b,
std::string::const_iterator e)
{
for (; a < b; a++)
{
if (*a == *(a + 1))
{
toupper(*a);
toupper(*(a + 1));
}
}
}

int main()
{
std::string in = "peppermint 1001 bubbles balloon gum", out(100, '*');
auto e = function(in.cbegin(), in.cend(), out.begin());

int n = e - out.begin();
std::string s = out.substr(0, n);
bool b = (s == "pePPermint 1001 buBBles baLLOOn gum");
std::cout << std::boolalpha << b << std::endl;
}

我做错了什么?

最佳答案

你有几个问题。

首先,您的函数 promise 返回 std::string::iterator

std::string::iterator function(....)
{
//... return statement is missing here!
}

你没有遵守 promise 。这将导致 undefined behaviour 。例如,在您的情况下,它只是编译而不给出输出。

为了获得定义的行为,您应该从函数返回

std::string::iterator function(...)
{
// ... code
return {}; // return appropriately iterator of std::string
}

其次,你想修改字符串的字符,这需要一个可修改的迭代器而不是std::string::const_iterator .

然后在循环中,你需要改变大写的char ector 通过重新分配给它。例如:

*a = toupper(*a);

第三,在函数的 for 循环中执行此操作时要小心

 for(; a < b; a++)
{
if(*a == *(a + 1)) // --->here
// ... code
}

a== str.end()-1 时会发生什么情况? ,你仍然会做增量(即 *(a + 1) ),对吧?再次递增结束迭代器 leads you Undefined behaviour .

在这种情况下,您可以使用 std::next 来自 <iterator> header 以安全地检查它。

下面是解决上述问题的演示代码:

#include <iostream>
#include <string>
#include <iterator> // std::next

std::string::iterator function(
std::string::iterator a,
std::string::iterator b,
std::string::iterator e)
{
auto beg = a;
for (; a < b; a++)
{
if (std::next(a) != b && *a == *std::next(a)) {
*a = toupper(*a);
*std::next(a) = toupper(*std::next(a));
}
}
std::cout << std::string{ beg, b };
return {}; // return appropriately iterator of std::string
}

现在打印:https://godbolt.org/z/ZsLHxw

pePPermint 1001 buBBles baLLOOn gum

我假设您希望以某种方式将输出输出到第三个函数参数 std::string::iterator e .我会让那部分让你弄清楚。同时,看看标准算法函数 std::transform ,这对于进行此类转换可能很方便。

关于c++ - 大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62607661/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com