我正在尝试将键盘的按键向右移动 2 位数字,例如,如果用户想要输入“a”,则必须按键盘上的“d”键,“p”到“]”。
这意味着如果用户输入是:“pm[ojku d, d]]'t/”,
那么输出将是:“我买了一个苹果”。
不包括键盘上该行中的大写键和最后一个键。
我这样做的方法是检查字符串的每个字符并将其 ASCII 与每种情况进行比较,它工作得很好。但这样做我觉得很愚蠢,想知道是否有任何算法或更聪明的方法来实现这一点。
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);
}
Run Code Online (Sandbox Code Playgroud)
这是使用查找表的通用替换函数。它应该能够完成这项工作。我已经填写了'd'和的转换's'。其余的你可以填写。表中的 NUL 字符表示不进行替换。
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);
}
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢写入新字符串,则可以使用它。即使输入和输出相同,它也会工作。
void replace(char *dest, const char *src, const char table[256])
{
while(*src) {
if(table[*src])
*dest = table[(unsigned char)*src];
src++;
dest++;
}
}
Run Code Online (Sandbox Code Playgroud)