Home > OS >  Replace element of a string
Replace element of a string

Time:12-06

I need to convert all uppercase letters to lowercase and vice-versa. If one of the elements of the string is not a valid letter of the alphabet, it must be replaced with “bug here!”. Using user-defined function

Input: evEry1
Output: EVeRY*bug here!*

I am already able to convert all uppercase letters to lowercase and vice-versa. I was also able to change nonalphanumeric elements to a single character but cannot replace it with the entire string "bug here!". I end up having error saying it cannot be converted

string flip (string w, int t){
    string ch = "*bug here!*";
    for (int j=0; j<w.length(); j  ){
        if (w[j] >= 'A' && w[j] <= 'Z')
            w[j] = w[j]   32;
        else if (w[j] >= 'a' && w[j] <= 'z')
            w[j] = w[j] - 32;
        else 
            w[j] = ch;
    }
    return w;
}

CodePudding user response:

A character is not a string and a string is not a character. So you can not replace characters with strings by using w[j] = ch;. Instead you should use the string replace method. Something like this

string flip (string w, int t){
    string ch = "*bug here!*";
    for (int j=0; j<w.length(); j  ){
        if (w[j] >= 'A' && w[j] <= 'Z'){
            w[j] = w[j]   32;
        }
        else if (w[j] >= 'a' && w[j] <= 'z') {
            w[j] = w[j] - 32;
        }
        else {
           w.replace(j, 1, ch);  // replace the character
           j  = ch.length() - 1; // advance j so we don't process the replacement string
        }
    }
    return w;
}

Note that after inserting the replacement string we have to increment j otherwise we'll start processing the replacement string.

This is untested code.

BTW given the confusion over strings vs characters, you really should change the name of the variable ch. How about str instead?

BTW I'm not seeing what the purpose of t is in the function above. It's not being used so it could be removed.

CodePudding user response:

When you index the string you are looking at a single character, so

w[j] = w[j] - 32;

is ok.

When you want to insert a substring, you need to use std::string's insert function:

w.insert(j, ch);

This will allocate the extra space needed since you have a string not a single character. You then need to skip j ahead by ch.length() to move to the next original character.

  • Related