在 C 中,指针是变量的地址,仅此而已。如果要比较字符串(在 C 中翻译为以空字符结尾的字符串),最好使用strcmp()
orstrncmp()
函数。
像这样的声明
char *found_char_location;
char *source_pt_cpy;
found_char_location = chars;
source_pt_cpy = source;
...
...
if(*found_char_location == *source_pt_cpy)
将比较存储在found_char_location
和source_pt_cpy
指针指向的位置中的单个值,在这种情况下是一个字符,我认为这不是你想要的!
这是我维护的自制字符串库中的代码片段(如果您想玩指针,请查看它!)
/*******************************************************************
* Return values
* - NULL in case any of the arguments is NULL
* - Modified string is returned
*
* Example Usage
* char str[] = "'free' as in 'free speech', not as in 'free beer'";
* printf("%s\n",zstring_replace_str(str,"free","KLMN"));
*
* Example Output
* 'KLMN' as in 'KLMN speech', not as in 'KLMN beer'";
******************************************************************/
char *zstring_replace_str(char *str, const char *x, const char *y){
/* to preserve the address of original pointers, tmp_ are used
* dummy_ptr enables us to preserve the address of tmp_str when
* a matching string pattern is found
* */
char *tmp_str = str, *tmp_x = x, *dummy_ptr = tmp_x, *tmp_y = y;
int len_str=0, len_y=0, len_x=0;
/* NULL pointer check */
if ((*str && *x && *y)==0)
return 0;
/* calculating length of strings */
for(; *tmp_y; ++len_y, ++tmp_y)
;
for(; *tmp_str; ++len_str, ++tmp_str)
;
for(; *tmp_x; ++len_x, ++tmp_x)
;
/* Bounds check */
if (len_y >= len_str)
return str;
/* reset tmp pointers */
tmp_y = y;
tmp_x = x;
for (tmp_str = str ; *tmp_str; ++tmp_str)
if(*tmp_str == *tmp_x) {
/* save tmp_str */
for (dummy_ptr=tmp_str; *dummy_ptr == *tmp_x; ++tmp_x, ++dummy_ptr)
if (*(tmp_x+1) == '\0' && ((dummy_ptr-str+len_y) < len_str)){
/* Reached at the end of x, we got something to replace
* then!
* Copy y only if there is enough room for it
*/
for(tmp_y=y; *tmp_y; ++tmp_y, ++tmp_str)
*tmp_str = *tmp_y;
}
/* reset tmp_x */
tmp_x = x;
}
return str;
}
它并不能完全按照您的意愿行事,但会让您了解如何完成任务。
在上面的代码中,for
循环
for (dummy_ptr=tmp_str; *dummy_ptr == *tmp_x; ++tmp_x, ++dummy_ptr)
做你想做的事。它从源字符串的开头(for
循环的初始化)开始,然后在其逻辑检查部分比较指针tmp_x 和 dummy_ptr指向的当前字符。最后,循环递增两个指针以遍历整个字符串。
这是另一个在字符串中搜索字符而不是字符串的示例。此代码也来自zString 库。
/* First if check can be omitted to improve the performance */
int zstring_search_chr(char *token,char s){
if (!token || s=='\0')
return 0;
for (;*token; token++)
if (*token == s)
return 1;
return 0;
}