簡體   English   中英

用給定字符串的字母表中的 position 替換每個字母

[英]Replace every letter with its position in the alphabet for a given string

第一步,我將字符串更改為小寫,之后我從字符串中刪除了所有非字母,現在我正在努力用字母 position 替換每個字母。 有誰知道怎么做這樣的事情? 謝謝!

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 output 123,然后是很多數字32761004966.....

您的代碼中有幾個問題:

  1. 您的主要錯誤是在這一行:

    for (int z: aplha_numbers)

    您 go 在分配的數組中的所有 100 個元素上,而不僅僅是有效條目。 在我的解決方案中,根本不需要這樣的數組。 stringstream對象直接更新。

  2. 小寫字符c的 position 只是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;
}

Output:

in:AbC, out:123

附注:最好避免using namespace std; . 見這里: 為什么“使用命名空間標准;” 被認為是不好的做法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM