字符串惯用法笔记
字符串的惯用法有很多,这里总结最常用的两种。
第一、字符串末尾的搜索
考虑编写strlen函数,这是最直接的方法:
size_t strlen(const char *s)
{
size_t n;
for(n = 0; *s != '\0'; s++)
n++;
return n;
}
可以改进使程序更加简洁:
size_t my_strlen(const char *s)
{
size_t n = 0;
while (*s++)
n++;
return n;
}
所以,搜索字符串末尾的惯用法为:
while (*s)
s++;
或者:
while (*s++)
;
但是第一种方法指向空字符,第二种方法指向空字符后面的位置。
第二、复制字符串惯用法
先看基本的strcat函数:char *strcat(char *s1, const char *s2)
{
char *p = s1;
while (*p)
p++;
while (*p++ = *s2++)
;
return s1;
}
所以,字符串复制的惯用法为:
while (*p++ = *s2++)
;
注意是赋值语句,有些编译器可能会有警告。可以写成:
while ((*p++ = *s2++) != 0)
对应GCC编译器,可以用一下格式消除警告:
while((*p++ = *s2++))