題目信息:參考鏈接
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct{
char name[100];
char num[100];
}rule;
void urlMap();
char *strApt(char *str);
void putRst(char *, char *);
//URL映射 !!!error:變量賦值前使用
void urlMap(){
int n, m, i, j, x, mapi, tmp;
char str[101];
char map[50];
char *s;
rule *r;
scanf("%d %d", &n, &m);
r = (rule *)malloc(n * sizeof(rule));
for(i = 0; i < n; i++){
scanf("%s %s", r[i].num, r[i].name);
//r[i].num = strApt(r[i].num);
strcpy(r[i].num, strApt(r[i].num));
}
while(m){
scanf("%s", str);
x = 0;//第x條規則
lab:
i = 0; j = 0; s = r[x].num; mapi = 0;//開始匹配
memset(map, 0, 50);//!!!error
while(str[i] != '\0' && s[j] != '\0'){
if(s[j] != ',' && s[j] != ';' && s[j] != ':'){
if(str[i] == s[j]){
i++; j++;
}
else{
x++;//匹配失敗,指向下一條規則或url
if(x == n) {printf("404\n"); goto next;}
else goto lab;
}
}
else{
if(s[j] == ',' && str[i] >= '0' && str[i] <= '9'){//int
j++; tmp = 0;
while(str[i] == '0'){//<int>
i++; tmp = 1;
}
if(tmp == 1) {map[mapi] = i - 1; tmp = 0;}
else map[mapi] = i;
mapi++;//start
while(str[i] >= '0' && str[i] <= '9'){
i++;
}
map[mapi] = i - 1; mapi++;//stop
//匹配到的<int>索引
}
else if(s[j] == ';' && str[i] != '/'){//path 匹配至url末尾
j++;
map[mapi] = i; mapi++;
while(str[i] != '\0'){
i++;
}
map[mapi] = i - 1;//url匹配成功
printf("%s ", r[x].name);
putRst(map, str);
goto next;
}
else if(s[j] == ':' && str[i] != '/'){//str
j++;
map[mapi] = i; mapi++;
while(str[i] != '/'){
i++;
}
map[mapi] = i - 1; mapi++;
}
else{
x++;//匹配失敗,指向下一條規則或url
if(x == n) {printf("404\n"); goto next;}
else goto lab;
}
}
//s = r[j].num;
}
if(str[i] == '\0' && s[j] == '\0'){
printf("%s ", r[x].name);
putRst(map, str);//匹配成功
}
else{
x++;//匹配失敗,指向下一條規則或url
if(x == n) {printf("404\n"); goto next;}
else goto lab;
}
next:
m--;
}
}
//處理規則串,替換<int>
char *strApt(char *str){
int i = 0, j = 0;
char *new = (char *)malloc(100);
while(str[i] != '\0'){
if(str[i] == '<'){
i++;
switch(str[i]){
case 'i':new[j] = ','; i = i + 3; break;//int
case 'p':new[j] = ';'; i = i + 4; break;//path
case 's':new[j] = ':'; i = i + 3; break;//str
}
}
else{
new[j] = str[i];
}
i++;
j++;
}
new[j] = '\0';
return new;
}
void putRst(char *map, char *str){
int i = 0, j;
while(map[i] != 0){
if(str[map[i]] == '0' && str[map[i] + 1] >= '1' && str[map[i] + 1] <= '9'){
(map[i])++;//消除前導0
}
for(j = map[i]; j <= map[i + 1]; j++){
printf("%c", str[j]);
}
if(map[i + 2] == 0){
printf("\n");
}
else{
printf(" ");
}
i += 2;
}
}
int main(){
urlMap();
return 0;
}