【问题标题】:C++: capitalizing a character using another characterC ++:使用另一个字符大写一个字符
【发布时间】:2018-08-28 01:05:27
【问题描述】:

我正在尝试创建一个函数,在输入“^”字符后将字符串中的下一个字符大写。代码如下所示:

void decodeshift( string orig, string search, string replace )
{
    size_t pos = 0;

    while (true) {
    pos = orig.find(search, pos);
    if(pos == string::npos)
        break;
    orig.erase(pos, search.length());
    orig.replace(pos, search.length(), replace);

    cout<<orig<<endl;
    }
}

int main()
{
    string question = "What is the message? ";
    string answer = "The real message is ";

    string shift="^";
    string test="a";

    string answer1;

    //output decoded message
    string answer2;

    cout << question;
    cin >> answer1;
    cout << "decoding . . . " << "\n";

    //decodeback(answer1, back);
    decodeshift(answer1, shift, test);
    return 0;
}

我的输入将是:

^hello

想要的输出:

Hello

电流输出

aello

我似乎找不到要使用的正确功能,而且我对如何在这种情况下使用 toupper 感到困惑。我只需要找到合适的替代品。

【问题讨论】:

  • 您可能会考虑花一点时间阅读导览并在minimal reproducible example 上工作。 toupper 对此很好,但是由于您的代码无法编译,因此很难知道您遇到问题的原因。
  • 我尝试使用占位符字符串而不是大写字母,效果很好。我只是在寻找一种使用 toupper 而不是单个字符的方法,除非我使用 26 个单独的 if 语句。
  • 我不明白你在说什么占位符字符串或 26 个 if 语句。这是一个简单的问题,我相信我们可以帮助您解决它,但是您需要先提供您真正的可编译代码,这样我们才能看到发生了什么。 ideone.com/dJZCBI
  • 修复它,所以每当“^”出现时,下一个字符被“a”替换。所以我只是想找到一种方法让它变成大写。

标签: c++ text character


【解决方案1】:

试试这样的:

#include <cctype>

void decodeshift( string orig, string search )
{
    size_t pos = orig.find(search);
    while (pos != string::npos)
    {
        orig.erase(pos, search.length());
        if (pos == orig.size()) break;
        orig[pos] = (char) std::toupper( (int)orig[pos] );
        pos = orig.find(search, pos + 1);
    }
    return orig;
}

...

answer1 = decodeshift(answer1, "^");
cout << answer1 << endl;

或者,干脆去掉shift参数:

#include <cctype>

string decodeshift( string orig )
{
    size_t pos = orig.find('^');
    while (pos != string::npos)
    {
        orig.erase(pos, 1);
        if (pos == orig.size()) break;
        orig[pos] = (char) std::toupper( (int)orig[pos] );
        pos = orig.find('^', pos + 1);
    }
    return orig;
}

...

answer1 = decodeshift(answer1);
cout << answer1 << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2010-10-29
    • 1970-01-01
    • 2021-06-15
    • 2023-02-23
    相关资源
    最近更新 更多