Home > OS >  trying to replace the letter in string name which contains german letters to Uppercase, won't w
trying to replace the letter in string name which contains german letters to Uppercase, won't w

Time:03-30

what is wrong with this code? It does not work as I want to if there is a letter in a string such as å,ä,ö, make them to uppercase. Is there something I'm missing? Is there any way in C to make German letters to uppercase in some way with the library? Please share with me if you know how to solve this problem thank you!

string makeUpperCase(string c)
{
        transform(c.begin(), c.end(), c.begin(), ::toupper);
        while(c.find("Ä") != string::npos)
        {
                c.replace(c.find("Ä"), 2, "ä");
        }
        while(c.find("Å") != string::npos)
        {
                c.replace(c.find("Å"), 2, "å");
        }
        while(c.find("Ö") != string::npos)
        {
                c.replace(c.find("Ö"), 2, "ö");
        }

return c;
}

CodePudding user response:

You are searching for uppercase letters and replacing them with lowercase letters.

If you want to make the letters to uppercase, you have to do the opposite.

string makeUpperCase(string c)
{
        transform(c.begin(), c.end(), c.begin(), ::toupper);
        while(c.find("ä") != string::npos)
        {
                c.replace(c.find("ä"), 2, "Ä");
        }
        while(c.find("å") != string::npos)
        {
                c.replace(c.find("å"), 2, "Å");
        }
        while(c.find("ö") != string::npos)
        {
                c.replace(c.find("ö"), 2, "Ö");
        }

        return c;
}

CodePudding user response:

On many platforms, the function toupper can also deal with German characters. However, it does not do this in the default "C" locale. You will therefore have to change the locale to German. You can do this with the function std::setlocale.

Which locales are available and what their names are, is not specified by the ISO C standard. However, on both Linux and Windows, you can write

std::setlocale( LC_ALL, "de-DE" );

to set the locale to German.

Here is an example program:

#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
#include <clocale>

int main( void )
{
    //define text string with German-specific characters
    std::string str{ "This is a test string with ä, ö and ü." };

    //set the locale to German
    std::setlocale( LC_ALL, "de-DE" );

    //convert string to upper-case
    std::transform( str.begin(), str.end(), str.begin(), static_cast<int(*)(int)>(std::toupper) );

    //output converted string
    std::cout << str << '\n';
}

This program has the following output:

THIS IS A TEST STRING WITH Ä, Ö AND Ü.

As you can see, also the German letters were made upper-case.

  • Related