I have to display some sentences on a screen. However, the language can change if the user want to, so I do not want but I can do that :
if(language==1)
{
printf("Hello sir");
}
else if(language==2)
{
printf("Hola senor");
}
OR
printf("%s",language == 1 ? "Hello sir" : "Hola senor");
I do not want that because I have a lot of iterations. Can I use map or enum and change it during code is running, I was thinking about a things like that :
#define MESSAGE_HELLO "Hello sir" OR "Hola senor"
printf("%s",MESSAGE_HELLO);
Do you have an idea ? Can you help me please ?
CodePudding user response:
You probably can create two maps for the words you want to translate - one map for one language - and then create a pointer to one of the maps. Then use pointer and [] to take words you need. Also, the pointer can be changed so that it points to another map at any moment.
CodePudding user response:
In the professional world, I have often used tables (arrays) of phrases. Each slot in the array represents the phrase in another language.
static const char str_hello[] =
{
/* English */ "hello",
/* Spanish */ "hola",
/* German */ "guten tag",
//...
};
This has worked well in embedded systems.
CodePudding user response:
You can use some internationalization library that might help you. But here I will focus on how one can solve such a problem. Naturally, you need to have a set of languages, a set of message keys and a relationship between message keys and the languages, which would hold the actual message. Let's see some solutions:
Language file
You can store english.txt, etc. which would look like this:
hello="Hello"
world="World"
and some other language, hungarian.txt for example:
hello="Heló"
world="Világ"
etc.
Now, you can create an array of Map<String, Map<String, String>>
, loop the languages, for each language process the corresponding file and fill the map accordingly.
Database
You can store a languages table, a message_keys table and a messages table. The messages table would have a foreign key pointing to languages and another one to message_keys and the actual message would be stored there as well. You could have an API that you could use in order to request items or groups of messages in a certain language.
There are many possible solutions.