函數的原型為:
int diff_str(const char * a, const char * b);
主要是用來處理當A和B 中存在有符號點 “.” 或星號 “*”時的判斷關系。
星號出現的(位置不定),且 (不限制長度) 匹配 [a-z0-9] 中包含的字符。
注意: 星號不能匹配 "."
例如:
a=“hello*world”;
b=“hello.world”;
這個時候 a != b;
a=“hello*world”;
b=“hellower9world”;
這個時候 a == b;
a="*";
b="adfafdafd";
這個時候 a == b;
最好再加個判斷如果 輸入 的a 非 [a-z0-9.] 直接返回。
要求性能高效。
思路我有,關鍵是求一個效率高的算法。求代碼:
int n=0, d=0;
for (p1 = a, p2= a + strlen(a) - 1; p2 > p1; ++p1, --p2){
if (*p1 == '*'){
if (!strncmp(a, b, n)){
d=1;
}
break;
} else if (*p2 =='*'){
if (!strncmp(a, b,strlen(a)-n-1)){
d=1;
}
break;
}
n++;
}
定位"*" 號位置我只知道這樣兩邊查找。
求更高效的。
#include <stdio.h>
int diff_str(const char *a, const char *b)
{
const char *s = a;
const char *t = b;
for (;; s++, t++)
{
if (*s == NULL && *t == NULL)
return 1;
else if (*s == NULL || *t == NULL)
return 0;
if (*s == *t)
continue;
if (*s == '*')
{
if (*t == '.')
return 0;
if (diff_str(s, t + 1))
return 1;
else if (*(s + 1) == *t)
{
s++;
if (*s == NULL)
return 1;
}
}
else
return 0;
}
}
void d(const char *a, const char *b)
{
int r = diff_str(a, b);
if (r)
printf("'%s' matches '%s'\n", a, b);
else
printf("'%s' DOES NOT match '%s'\n", a, b);
}
int main()
{
d("", "");
d("*", "");
d("*", "t");
d("t", "t");
d("*t", "st");
d("*t", "sat");
d("s*t", "sat");
d("sa*", "sat");
d("s*", "sat");
d("s*t*s", "satas");
d("s*t*s", "sata1s");
d("s*t*s", "sats");
d("s*t*s", "sts");
d("s*t*s", "sat.s");
d("s*t*s", "sata");
d("s*t*s", "sat");
d("s*t*s", "saas");
d("s*s", "satatatas");
d("s*tas", "satatatas");
d("s*tatas", "satatatas");
d("s*tatatas", "satatatas");
d("s*tatatatas", "satatatas");
printf("=====================================\n");
d("au*ex*.bat", "autoexec.bat");
d("au*e*.bat", "autoexec.bat");
d("au*.bat", "autoexec.bat");
d("au**.bat", "autoexec.bat");
d("au*ex*bat", "autoexec.bat");
d("au*ex*.b*t", "autoexec.bat");
d("au*ex*.*", "autoexec.bat");
d("*.*", "autoexec.bat");
printf("=====================================\n");
getchar();
}
結果
'' matches ''
'*' DOES NOT match ''
'*' matches 't'
't' matches 't'
'*t' matches 'st'
'*t' matches 'sat'
's*t' matches 'sat'
'sa*' matches 'sat'
's*' matches 'sat'
's*t*s' matches 'satas'
's*t*s' matches 'sata1s'
's*t*s' matches 'sats'
's*t*s' matches 'sts'
's*t*s' DOES NOT match 'sat.s'
's*t*s' DOES NOT match 'sata'
's*t*s' DOES NOT match 'sat'
's*t*s' DOES NOT match 'saas'
's*s' matches 'satatatas'
's*tas' matches 'satatatas'
's*tatas' matches 'satatatas'
's*tatatas' matches 'satatatas'
's*tatatatas' DOES NOT match 'satatatas'
=====================================
'au*ex*.bat' matches 'autoexec.bat'
'au*e*.bat' matches 'autoexec.bat'
'au*.bat' matches 'autoexec.bat'
'au**.bat' matches 'autoexec.bat'
'au*ex*bat' DOES NOT match 'autoexec.bat'
'au*ex*.b*t' matches 'autoexec.bat'
'au*ex*.*' matches 'autoexec.bat'
'*.*' matches 'autoexec.bat'
=====================================
尚有個小問題 可以代替0個字符麼?如果可以的話,那麼結果'' DOES NOT match ''有誤;如果不可以,則's*t*s' matches 'sts'有誤