Home > Software design >  Finding and changing repeated letters in a word
Finding and changing repeated letters in a word

Time:12-05

I'm trying to create logic that goes through the word and tries to find if there are letters, that are used more than once. If a letter repeats, then change it to "1", if it's not then change it to "2". Example: Radar - 11211, Amazon - 121222, karate - 212122. Specific problem is that if I use for(), each letter compares to the last one. Also I don't understand how can I check last letter by using for(). Last letter is always 2.

Here is my code:

#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; 
}

Example: test returns 1e22 instead of 1221

CodePudding user response:

You have undefined behavior in your program when wrote word[i 1]; inside the for loop. This is because you're going out of bounds for the last value of i by using i 1.

One possible way to solve this would be to use std::map as shown below. In the program given std::tolower is used because you want capital and small letters to be treated the same.

#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;
}

The output of the program can be seen here.

Output for the input Amazon is:

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