将给定字符串的每个字母替换为其在字母表中的位置



第一步,我将字符串更改为小写,之后我从字符串中删除了所有非字母,现在我正在努力用字母表位置替换每个字母。有人知道怎么做吗?谢谢你!

string alphabet_position(string message){
string alphabet= "abcdefghijklmnopqrstuvwxyz";
int aplha_numbers[100];
for_each(message.begin(), message.end(), [](char & c){
c = ::tolower(c);
});
for(int i=0; i< message.size(); i++){
if(message[i] < 'a' || message[i] > 'z'){
message.erase(i, 1);
i--;
}
}
for(int j=0; j<message.size(); j++){
int index = alphabet.find(message[j]);
aplha_numbers[j]= index +1;

}
std::ostringstream os;
for(int z: aplha_numbers){
os<<z;
}
std::string str(os.str());
return str;
}

现在我有一个不同的问题,我得到了字母表的位置,但我也得到了很多垃圾值后的最后一个字母。例如:输入:abc输出123和之后的许多数字32761004966.....

您的代码中有几个问题:

  1. 你的主要错误是在这一行:

    for (int z : aplha_numbers)

    您遍历分配的数组中的所有100个元素,而不仅仅是有效的条目。在我的解决方案中,根本不需要这样的数组。直接更新stringstream对象

  2. 小写字符c的位置简写为c-'a'+1。不需要查找表(至少假设输入是ascii)。

  3. 实际上不需要通过将其变为小写来更改输入字符串。这可以在您遍历它时动态地完成。

这是一个完整的固定版本:

#include <string>
#include <sstream>
#include <iostream>
#include <cctype>
std::string alphabet_position(std::string message) 
{
std::ostringstream os;
for (auto const & c : message)
{
char c_lower = std::tolower(c);
if (c_lower < 'a' || c_lower > 'z')  continue;
int pos = c_lower - 'a' + 1;
os << pos;
}
return os.str();
}
int main()
{
std::string s_in = "AbC";
std::string s_out = alphabet_position(s_in);
std::cout << "in:" << s_in << ", out:" << s_out << std::endl;
return 0;
}

输出:

in:AbC, out:123

旁注:最好避免使用using namespace std;。为什么使用命名空间std;"被认为是不好的做法?

相关内容

最新更新