例1 计算字符串长度:
int strlen(char *str)
{
int len = 0;
while(*str++ != '\0') //比较str[i]不为'\0'时,指向下一个位置
len++; //计算长度
return len;
}
例2 查找字符串中是否含有目标字符:
/*在字符串中查找特定的字符*/
int find_char(char **str, char value)
{
char *string_t;
int val_pos = 0;
assert(str != NULL); //确认字符串非空,头文件 #include "assert.h"
while((string_t = *str++) != NULL) //字符串非空
{
while(*string_t != '\0') //字符串未到结尾,则继续查找
{
val_pos++;
if(*string_t++ == value)
{
return val_pos;
}
}
}
return -1;
}
调用:
int main(void)
{
char *str = "MacroSilicon";
//char **str_str = {"MacroSilicon", "shao"}; //这种方式初始化错误,为什么错误
char *str_str[]={ "MacroSilicon", "shao", NULL };
printf("str length: %d\n", strlen(str));
printf("str length: %d\n", find_char(str_str, 'S'));
return 0;
}