Home > Mobile >  Converting German Letters to Uppercase won't work
Converting German Letters to Uppercase won't work

Time:03-30

What is wrong with this code? It does not make them to uppercase, as I want to, if there is a letter in a string such as å, ä or ö. Is there something I'm missing?

Is there any way in C to make German letters to uppercase in some way with the library?

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, in the default "C" locale, it only considers the characters a to z and A to Z to be alphabetical letters. You will therefore have to change the locale to German, so that the function also considers German letters to be valid alphabetical letters. 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 Microsoft 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 on Microsoft Windows:

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

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

For setting the locale to German on Linux, see the Linux documentation for setlocale.

  • Related