这是我的代码,我现在真的陷入困境。 问题是,用户输入莫尔斯电码,然后通过标记将每个电码存储在数组中,现在我的问题是,如何在存储每个标记的数组中搜索特定字符串?
例如我输入:....。 .-.. .-.. ---/.-- --- .-. .-.. -..
作为我的莫尔斯电码,然后将其标记化。
现在我想在数组中的每个标记中搜索特定字符串,例如:
我将搜索“....”,如果它搜索到一个,它会打印出 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;
}
最佳答案
试试这个--->
- 可以使用
strstr
来查找子字符串。 - 初始化一个计数索引来查找位置,
关于c - 在数组中搜索特定标记/字符串 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397043/