C++ 将下一个字符添加到字符串C++;

C++ 将下一个字符添加到字符串C++;,c++,C++,我确实得到了字符串(hello-->ifmmp)上的下一个字符,但是在hello*的情况下,我希望仍然能够将*显示为例外,它也可以是一个数字,但我想这并不重要,因为它不在字母表中 这是我的代码,else if应该在哪里? 还有另一个选项,但我不认为它是优化的,它是在第一个for循环中添加: string other="123456789!@#$%^&*()"; for(int z=0;z<other.length();z++) { if(str[i]==ot

我确实得到了字符串
(hello-->ifmmp)
上的下一个字符,但是在hello*的情况下,我希望仍然能够将*显示为例外,它也可以是一个数字,但我想这并不重要,因为它不在字母表中

这是我的代码,else if应该在哪里? 还有另一个选项,但我不认为它是优化的,它是在第一个for循环中添加:

string other="123456789!@#$%^&*()";

 for(int z=0;z<other.length();z++)
   {
       if(str[i]==other[z])
       str2+=other[z];
   }
string other=“123456789!@$%^&*()”;

对于(intz=0;z,标准库中有一个函数
isalpha
,它对分类非常有用

你可以这样做

(这类练习通常假定英语字母采用ASCII编码,这是一种非常特定于ASCII的解决方案。如果您需要不同的字母或字符编码,您需要自己处理。)


我喜欢函数。它们可以解决很多问题。例如,如果你把你已有的代码粘贴到一个函数中,并对它进行一些调整

char findreplacement(char ch, const std::string & alphabet)
{
    for (int j = 0; j < alphabet.length(); j++)
    {
        if (ch == alphabet[j])
        {
            return alphabet[(j+1) % alphabet.length()]; 
            // return the replacement character
            // using modulo, %, to handle wrap around z->a
        }
    }
    return ch; // found no replacement. Return original character.
}

它更干净,更难搞砸。

我觉得你的措辞不太清楚-你能提供一些输入字符串、你想要的输出和你目前得到的输出的例子吗?你的程序的实际输出是什么?预期输出是什么?你的程序的目的是什么?它应该解决什么问题?什么你应该回答的作业或练习是什么?你有没有尝试过在调试器中逐步检查代码以了解其功能?请花一些时间阅读相关内容,以及。您好,如果我的英语不是很好,我很抱歉,我的输入是Hello,而输出是ifmmp,我试图实现的是获得相同的结果,但如果我有我在这个词中包含了一种特殊的字符,忽略它并将其添加到输出。我不知道是否在解释。<代码> ZZZ<<代码>的输出应该是AAAA,但是在这种情况下,该选项不能被执行。您可能需要添加一个注释,说明这是非常ASCII专用的,并且C++规范对于其他的Encod是开放的。是的。
#include <cctype>
#include <string>
#include <iostream>

int main()
{
    std::string str = "Hello*Zzz?";
    std::string str2;
    for (char c: str)
    {
        if (std::isalpha(c))
        {
            c += 1;
            if (!std::isalpha(c)) 
            {
                 // Went too far; wrap around to 'a' or 'A'.
                 c -= 26;
            }
        }
        str2 += c;
    }
    std::cout << str2 << std::endl;
}
Ifmmp*Aaa?
char findreplacement(char ch, const std::string & alphabet)
{
    for (int j = 0; j < alphabet.length(); j++)
    {
        if (ch == alphabet[j])
        {
            return alphabet[(j+1) % alphabet.length()]; 
            // return the replacement character
            // using modulo, %, to handle wrap around z->a
        }
    }
    return ch; // found no replacement. Return original character.
}
for (int i = 0; i < str.length(); i++)
{
    str2 += findreplacement(str[i], alphabet);
}
for (char ch: str)
{
    str2 += findreplacement(ch, alphabet);
}