【发布时间】:2014-01-28 04:48:29
【问题描述】:
这是我现在真正陷入困境的代码。 问题是,用户输入一个摩尔斯电码,然后通过对其进行标记将其存储在一个数组中,现在我的问题是,我将如何在存储每个标记的数组中搜索特定字符串?
例如,我输入:.... . .-.. .-.. --- / .-- --- .-. .-.. -.. 作为我的摩尔斯电码,然后将其标记化。
现在我想在数组中的每个标记中搜索特定字符串,例如:
我将搜索“....”,然后如果它搜索到一个,它将打印出 H,依此类推,直到它形成单词。
字母表中的所有字母和数字也是如此。
#include <stdio.h>
#include <string.h>
#define LIMIT 200
int main(){
char morse[LIMIT],*decoded[300];
char *token;
int i=0,c;
printf("Enter morse code: ");
gets(morse);
token = strtok(morse, " ");
while( token != NULL){
//printf("%s\n",token);
//strcpy(decoded[i],token);
decoded[i++] = token;
token = strtok(NULL, " ");
}
if(strcmp(decoded[i],"....")==0){
printf("HELLO");
};
//for(i=0;i<sizeof(decoded);i++){
// printf("%s\n",decoded[i]);
//}
system("pause");
return 0;
}
编辑
#include <stdio.h>
#include <string.h>
#define LIMIT 200
int main(){
char morse[LIMIT],*temp[300],decoded[LIMIT];
char *token;
int i=0,c;
printf("Enter morse code: ");
gets(morse);
token = strtok(morse, " ");
while( token != NULL){
//printf("%s\n",token);
//strcpy(temp[i],token);
temp[i++] = token;
token = strtok(NULL, " ");
}
for(i=0;temp[i]!='\0';i++){
if(strstr(temp[i],".-")){
printf("A");
} else if(strstr(temp[i],"-...")){
printf("B");
}else if(strstr(temp[i],"-.-.")){
printf("C");
}
else if(strstr(temp[i],"-..")){
printf("D");
}
else if(strstr(temp[i],".")){
printf("E");
}
else if(strstr(temp[i],"..-.")){
printf("F");
}
else if(strstr(temp[i],"--.")){
printf("G");
}
else if(strstr(temp[i],"....")){
printf("H");
}
else if(strstr(temp[i],"..")){
printf("I");
}
else if(strstr(temp[i],".---")){
printf("J");
}
else if(strstr(temp[i],"-.-")){
printf("K");
}
else if(strstr(temp[i],".-..")){
printf("L");
}
else if(strstr(temp[i],"--")){
printf("M");
}
else if(strstr(temp[i],"-.")){
printf("N");
}
else if(strstr(temp[i],"---")){
printf("O");
}
else if(strstr(temp[i],".--.")){
printf("P");
}
else if(strstr(temp[i],"--.-")){
printf("Q");
}
else if(strstr(temp[i],".-.")){
printf("R");
}
else if(strstr(temp[i],"...")){
printf("S");
}
else if(strstr(temp[i],"-")){
printf("T");
}
else if(strstr(temp[i],"..-")){
printf("U");
}
else if(strstr(temp[i],"...-")){
printf("V");
}
else if(strstr(temp[i],".--")){
printf("W");
}
else if(strstr(temp[i],"-..-")){
printf("X");
}
else if(strstr(temp[i],"-.--")){
printf("Y");
}
else if(strstr(temp[i],"--..")){
printf("Z");
}else if(strstr(temp[i],"/")){
printf(" ");
}else{
printf("ERROR");
}
//printf("%s",strstr(temp[i],"...."));
}
//for(i=0;i<sizeof(temp);i++){
// printf("%s\n",temp[i]);
//}
system("pause");
return 0;
}
【问题讨论】:
-
在你的第二个代码块中,如果你没有学习过结构,你需要使用结构类型的数组或两个并行数组,这样你就不会写出几乎相同的代码27 次。如果你已经正确标记,你应该使用
strcmp()而不是strstr();您想打印与字符串完全匹配的字母,否则,E 之后包含点的每个字母都显示为 E(幸运的是,T 接近字母表的末尾,但每个字母 U-Z 的摩尔斯电码包含一个破折号,将被视为 T)。 -
您也没有在
strtok()循环之后分配temp[i] = NULL;,因此您的下一个循环不能保证及时终止。实际上,您可以使用for (int j = 0; j < i; j++)之类的循环来代替for (i = 0; temp[i] != NULL; i++),因为i包含正确的数字。