所以我试图通过创建一个基本函数strend
来获得指针/数组的掌握,如果在给定字符串的末尾出现子字符串,则返回1
,否则返回0
。我意识到我可以通过测量一个char数组的长度,从这个长度减去子串的长度,并在那里启动我的程序来完成这个任务,但我希望按照我的函数来获得更强的抓握指针算术。因此,这里的程序:指针字符串解析算法
#include <stdio.h>
#define NELEMS(x) (sizeof(x)/sizeof(x[0]))
int strend(char *string, char *substring, int substringLength){
int count; /*keep track of how many number of chars that match in a row*/
while(*string != '\0'){
count = 0;
while(*string == *substring){
if (count + 1 == substringLength) return 1; /*if matches = length of str*/
count++;
string ++;
substring ++;
}
if (count == 0) string++; /*only increment outer loop if inner loop has done no work*/
else {
substring - count; /*reset substring, don't increment string... BUGGY*/
}
}
return 0;
}
int main(){
char string[] = "John Coltrane";
char substring[] = "Coltrane";
int substringLength = NELEMS(substring);
printf("%d \n", strend(string, substring, substringLength));
char string2[] = "John Coltrane is Awesome Coltrane";
char substring2[] = "Coltrane";
int substringLength2 = NELEMS(substring);
printf("%d \n", strend(string2, substring2, substringLength2));
return 1;
}
在第一次测试字符串,字符串,字符串,我得到正确的结果,返回1,因为“雷恩”是在字符串的结尾。同样,如果我从string2中取出“Coltrane”,我会得到正确的结果,返回0,因为字符串不会以Coltrane结尾。
但是,对于上面看到的string2版本,我也会得到零,问题在于strend
在我迭代它之后不会重置substring
,并在它匹配主串的一部分时递增它。当子字符串的第一个实例位于字符串的末尾时,这没有问题,但是当有两个实例时(如在string2中)时没有。我认为substring - count
会将指针递减回到子字符串数组的开头,但它似乎没有这样做。
如果我用substring--
更改了该表达式,它确实显示了子字符串的最后一个字符,但像for(int i = 0; i < count; i++, substring--)
这样的表达式真的是唯一的方法吗?
编辑:更换substring - count
与for(; count > 0; count--, substring--)
似乎是一个非常优雅的班轮,它适用于我,但我仍然有一种直觉,有更好的办法。
这应该是' - ='(复合赋值)。 – Jon 2013-02-20 21:30:16