簡體   English   中英

查找和更改單詞中的重復字母

[英]Finding and changing repeated letters in a word

我正在嘗試創建遍歷單詞的邏輯,並嘗試查找是否有多次使用的字母。 如果一個字母重復,則將其更改為“1”,如果不是,則將其更改為“2”。 示例:雷達 - 11211,亞馬遜 - 121222,空手道 - 212122。具體問題是,如果我使用 for(),每個字母都會與最后一個字母進行比較。 另外我不明白如何使用 for() 檢查最后一個字母。 最后一個字母總是 2。

這是我的代碼:

#include <iostream>
#include <string>
using namespace std;
int main() 
{  string word;
    char bracket1('1');
    char bracket2('2');  
    cout << "Write your word: ";  
    cin >> word;        
    for (int i = 0; i < word.length(); ++i)  
    {
        char let1 = word[i];
        char let2 = word[i+1];
            if (let1 == let2)
            { word[i] = bracket1;}
            else 
             { word[i] = bracket2; }
         } cout << word; 
}

示例:測試返回 1e22 而不是 1221

一種可能的方法是使用std::map ,如下所示。 在給定的程序中使用std::tolower是因為您希望將大寫字母和小寫字母視為相同。

#include <iostream>
#include <map>
#include <algorithm>


int main()
{
    std::string word;
    std::cout << "Write your word: ";  
    std::getline(std::cin, word);
    
    //print out the word before replacing with 1 and 2 
    std::cout<<"Before transformation: "<<word<<std::endl;
    std::map<char, int> charCount; //this map will keep count of the repeating characters 
    
    //iterate through each character in the input word and populate the map 
    for(char &c: word)
    {
        charCount[std::tolower(c)]++;//increment the value by 1 
    }
    
    //replace the repeating characters by 1 and non-repeating by 2 
    for(char &c: word)
    {
        
        if(charCount.at(std::tolower(c)) > 1)
        {
            c = '1';
        }
        else 
        {
            c = '2';
        }
    }
    
    //print out the word after transformation
    std::cout<<"After transformation: "<<word<<std::endl;

    return 0;
}

程序的output可以看這里

輸入Amazon的 Output 是:

Write your word: Amazon
Before transformation: Amazon
After transformation: 121222

暫無
暫無

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

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