0

I have a string name2. I want to remove the capital characters in it and put lowercase instead.

Input:Car Output:car

Here is my loop code:-

 if(isupper(name2.at(i))) {
           string tem=to_string(tolower(name2.at(i)));
            name2.erase(i,1);
            name2.insert(i,tem);
        }

i is just the loop variable.

However , here is my input vs output

Input:Sushant Output:115ushant

It is giving some sort of ASCII equivalent ouput , I suppose. How do I fix this?

GameX
  • 57
  • 8
  • You can check how to make lowercase from https://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case – TheCoder Oct 08 '19 at 11:05
  • 1
    Possible duplicate of [How to convert std::string to lower case?](https://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case) – Alexander Oct 08 '19 at 11:08
  • You don't need to erase/insert, you can just set the value directly: `name2[i] = tolower(name[i])`. I suppose you are iterating over the string, are you (`for(size_t i = 0; i < name2.length; ++i)`)? Then you won't need range checking access (`at(i)`), you *know* you are in range, so prefer the more efficient non-checking index operator (`name2[i]`). – Aconcagua Oct 08 '19 at 11:11

2 Answers2

0

It can be done simply using the range-based for loop.

Here is a demonstrative program.

#include <iostream>
#include <string>
#include <cstring>

int main()
{
    std::string s;

    std::cout << "Enter a word: ";
    std::cin >> s;

    for ( char &c : s )
    {
        if ( std::isupper( ( unsigned char )c ) )
        {
            c = tolower( c );
        }
    }

    std::cout << s << '\n';
}

Its output might look like

Enter a word: Sushant
sushant

As for your if statement then at least this sub-statement

string tem=to_string(tolower(name2.at(i)));

does not make sense. For example

std::cout << std::to_string( 'A' ) << '\n';

can output

65

that corresponds to the ASCII value of the character 'A'.

That is the function std::to_string converts the promoted code of the character 'A' as an integer to a string.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Here, to_string interprets the result of tolower as an integer. So what you see inserted in your string is the ASCII value of 's' (115). To fix this, there is no need to convert to string, just use characters directly:

char c = tolower(name.at(i));
name2.erase(i, 1);
name2.insert(i, c);

Easier and more efficient would be to just directly tolower() the character at the ith position:

name[i] = std::tolower(name[i]);

That being said, simpler would be to lowercase the whole string in one go, and take for granted that some characters will be lowercased unnecessarily:

std::transform(name.begin(), name.end(), name.begin(), 
                [](unsigned char c){ return std::tolower(c); }
              );

See also: std::tolower.

Ton van den Heuvel
  • 10,157
  • 6
  • 43
  • 82