题解 | #配置文件恢复#
配置文件恢复
http://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
思路:
- 需要按照是否有空格来把命令区分为两类。
- 前一类仅有一个。
- 后一类按照空格所在的位置进行比较,注意需要判断比较符合的条件是否仅有一个,多个也应该视为unknown command(不知道)
#include <stdio.h>
static char *cmd1[6] = {"reset", "reset", "board", "board", "reboot", "backplane"};
static char *cmd2[6]= {"no use", "board", "add", "delete", "backplane", "abort"};
static int output_cmd(int flag)
{
switch(flag)
{
case 0:
printf("reset what\n");
break;
case 1:
printf("board fault\n");
break;
case 2:
printf("where to add\n");
break;
case 3:
printf("no board at all\n");
break;
case 4:
printf("impossible\n");
break;
case 5:
printf("install first\n");
break;
default:
printf("unknown command\n");
break;
}
return 0;
}
/* 判断字符串是否有空格,如果有,通过index_space参数获取空格位置 */
static int isSpace(char *str, int *index_space)
{
*index_space = 0;
if(!str)
{
return -1;
}
int flag_space = 0;
int len = strlen(str);
for(int i = 0; i < len; i++)
{
if(str[i] == ' ')
{
flag_space = 1;
*index_space = i;
break;
}
}
return flag_space;
}
int main()
{
char order[800][20];
memset(order , 0, 800*20*sizeof(char));
int index = 0;
while(gets(order[index]))
{
//printf("order[%d] = %s\n", index, order[index]);
index++;
}
//printf("index = [%d]\n", index);
int output[index][20];
memset(output , 0, index*20*sizeof(char));
for(int i = 0; i < index; i++)
{
int index_space = 0;
if(isSpace(order[i], &index_space) == 1)
{
/* 说明有空格 */
int flag = -1;
int count = 0;
for(int j = 1; j < 6; j++)
{
if(strncmp(order[i], cmd1[j], index_space) == 0
&& strncmp(order[i]+index_space+1, cmd2[j], strlen(order[i])-index_space-1) == 0)
{
count++; //如果有两个符合条件的,也要输出unknown command
flag = j;
}
}
if(count == 1 && flag >= 0)
{
output_cmd(flag);
}
else
{
output_cmd(6);
}
}
else
{
if(strncmp(order[i], cmd1[0], strlen(order[i])) == 0) //需要和输入的字符串长度比较
{
output_cmd(0);
}
else
{
output_cmd(6);
}
}
}
return 0;
}