I am trying to shift keyboard's key 2 digits to the right, for example if user wants to type "a" they have to press the "d" key on the keyboard, "p" to "]".
Which mean if the user input is: "p m[ojku d, d]]'t/",
then the output will be: "i bought an apple,".
Excluding the uppercase key and last the keys in its row on the keyboard.
The way I am doing it is to check every char of the string and compare its ASCII to each case, it works perfectly fine. But I feel so dumb by doing so, wanna know is there any algorithm or smarter way to accomplish this.
while (fgets(inputString, 500, stdin)) {
stringLength = strlen(inputString);
for (int i = 0; i < stringLength; i++) {
switch (inputString[i]) {
case 100:
outputString[i] = 'a';
break;
case 109:
outputString[i] = 'b';
break;
case 98:
outputString[i] = 'c';
case 47:
outputString[i] = ',';
break;
case 50:
outputString[i] = '`';
break;
case 92:
outputString[i] = '[';
break;
default:
outputString[i] = inputString[i];
}
}
printf("%s", outputString);
}
Here is a generic replace function using a lookup table. It should be able to do the job. I have filled in conversions for 'd'
and 's'
. You can fill in the rest. A NUL character in the table indicates no replacement.
const char table[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 32
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 48
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 64
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80
0, 0, 0, 0, 'a', 0, 's', 0, 0, 0, 0, 0, 0, 0, 0, 0, // 96
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 112
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240
};
void replace(char *str, const char table[256])
{
while(*str) {
if(table[*str])
*str = table[(unsigned char)*str];
str++;
}
}
int main(void)
{
char str[] = "dfdffd";
replace(str, table);
printf("%s\n", str);
}
If you prefer writing to a new string instead, you can use this. It will work even if input and output is the same.
void replace(char *dest, const char *src, const char table[256])
{
while(*src) {
if(table[*src])
*dest = table[(unsigned char)*src];
src++;
dest++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With