【问题标题】:Finding and changing repeated letters in a word查找和更改单词中的重复字母
【发布时间】:2022-01-10 12:01:09
【问题描述】:

我正在尝试创建遍历单词并尝试查找是否有多次使用的字母的逻辑。如果一个字母重复,则将其更改为“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

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    for 循环内写入word[i+1]; 时,您的程序中有未定义的行为。这是因为您使用 i+1 超出了 i 的最后一个值的范围。

    解决此问题的一种可能方法是使用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;
    }
    
    

    程序的输出可见here

    输入 Amazon 的输出是:

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

    【讨论】:

    • @Tartaro 不客气。如果对您有帮助,您能否将我的答案标记为正确。
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    相关资源
    最近更新 更多