使用C,我试图实现一个根据关键字string_word
将word
转换为mutated_word
的函数。例如:当word
是"HE"
时,使用密钥"QWERTYUIOPASDFGHJKLZXCVBNM"
,变异的单词应该变成"IT"
。但它不断给分割带来错误,不确定如何改进。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void) {
string word = "HE" ;
string string_word = "QWERTYUIOPASDFGHJKLZXCVBNM";
char mutated_word[strlen(word)];
for (int i = 0; word[i] != ' '; i++) {
string_word[(int)word[i] - 65] = mutated_word[i];
}
printf("%s", mutated_word);
}
- 您需要用null字符终止新字符串
- 你的数组太小
- 使用正确的索引类型(
int
不是正确的类型( - 检查字符是否为字母。如果没有决定要做什么(在我的例子中,我将所有字母转换为大写,其他字符保持原样(
- 不要使用幻数。使用
'A'
代替65
- 你的作业是错误的,你实际上想要的是正好相反的东西
- 它不适用于所有字符编码
#include <ctype.h>
#include <stdio.h>
int main (void)
{
string word = "HE" ;
string string_word = "QWERTYUIOPASDFGHJKLZXCVBNM" ;
char mutated_word [strlen(word) + 1];
size_t i;
for (i = 0; word[i] != ' '; i++)
{
if(isalpha((unsigned char)word[i]))
{
mutated_word[i] = string_word[toupper((unsigned char)word[i]) - 'A'];
}
else
{
mutated_word[i] = word[i];
}
}
mutated_word[i] = 0;
printf("%s", mutated_word);
}
https://godbolt.org/z/4zqq98Y3n
让它更便携:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
ptrdiff_t findIndex(const char ch, const char * restrict dict)
{
char *result = strchr(dict, ch);
if(!result) return -1;
return result - dict;
}
int main (void)
{
string word = "He124" ;
string string_word = "QWERTYUIOPASDFGHJKLZXCVBNM" ;
string dict = "ABCDEFGHIJKLMNOPQRSTUVXYWZ";
ptrdiff_t index;
char mutated_word [strlen(word) + 1];
size_t i;
for (i = 0; word[i] != ' '; i++)
{
if(isalpha((unsigned char)word[i]))
{
index = findIndex(toupper((unsigned char)word[i]), dict);
}
else index = -1;
mutated_word[i] = index == -1 ? word[i] : string_word[index];
}
mutated_word[i] = 0;
printf("%s", mutated_word);
}
https://godbolt.org/z/KW8TxxEvq
由于赋值顺序错误,程序崩溃:string_word[(int)word[i] - 65] = mutated_word[i];
正试图修改具有未定义行为的字符串文字。还要注意,对于null终止符,目标字符串必须长1字节,必须显式设置。
这里有一个更便携的版本:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *word = "HE";
const char *normal_word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *string_word = "QWERTYUIOPASDFGHJKLZXCVBNM";
char mutated_word[strlen(word) + 1];
unsigned char c;
const char *p;
size_t i;
for (i = 0; (c = word[i]) != ' '; i++) {
if (isupper(c) && (p = strchr(normal_word, c)) != NULL) {
c = string_word[p - normal_word];
} else
if (islower(c) && (p = strchr(normal_word, toupper(c))) != NULL) {
c = string_word[p - normal_word];
c = tolower(c);
}
mutated_word[i] = c;
}
mutated_word[i] = ' ';
printf("%sn", mutated_word);
return 0;
}