bool sstrcat( char *dest, int char_size, const char *src )
{
//扫描到dest终止符位置
int i = 0;
while( *dest )
{
++dest;
++i;
}
assert( i <= char_size );
//若src为空,不须拷贝,直接返回
if( !*src )
return true;
//把src拷贝到dest之后,覆盖dest的终止符
int j;
for( j = i; j < char_size; ++j )
{
*dest = *src;
if( !*src )
break;
++src;
++dest;
}
//若charsize过大,超过dest总长度,则会写到其他数据,报错
memset(dest, 0, char_size - j + 1 );
return true;
}
bool sstrcpy( char *dest, int char_size, const char *src )
{
//目的串和源串相等,不须拷贝
if( dest == src )
return true;
//逐个拷贝字符
int i;
for( i = 0; i < char_size; ++i )
{
*dest = *src;
//若源串遇到终止符,退出循环
if( !*src )
break;
++dest;
++src;
}
//若拷贝大于等于目的串的总长度,目的串没有空间存终止符,报错
assert( i < char_size );
return true;
}
bool sstrncpy( char *dest, int char_size, const char *src, int copy_size )
{
//拷贝的长度必须大于,小于目的串总长度,否则报错
assert( copy_size > 0 && copy_size < char_size );
//拷贝字符个数为参数copy_size的值
int i;
for( i = 0; i < copy_size; ++i )
{
//若源串遇到终止符,退出循环
if( !*src )
break;
*dest = *src;
++dest;
++src;
}
//加上目的串的终止符
*dest++ = 0;
return true;
}
char *sstrchr( const char *str, char c )
{
//若未到str终止符,搜索字符c
while( *str )
{
//到str终止符,搜索失败,返回Null
if( !*str )
return NULL;
//搜索成功,返回指向字符第一次出现的指针
if( c == *str )
return (char*)str;
str++;
}
}
char *sstrstr( const char *str, const char* substr )
{
//保存字符串和子字符串指针
const char *tempStr = str;
const char *tempSubstr = substr;
int i = 0;
while( *str )
{
//统计连续相等的字符个数
if( *substr == *str )
{
++i;
//连续相等字符个数等于字符串长度,搜索成功
if( i == strlen(tempSubstr) )
return (char*)tempStr;
++substr;
++str;
}
//不相等,母字符串后移一个,继续下一轮对比
else
{
i = 0;
substr = tempSubstr;
++tempStr;
str = tempStr;
}
}
return NULL;
}
int sstrlen( char *str )
{
//计算字符串长度,不包含终止符
int i = 0;
while( *str++ )
++i;
return i;
}
bool sstrset( char *str, int char_size, int c )
{
//把str里的所有字符都置为c,遇到终止符退出
int i;
for( i = 0; i < char_size; ++i )
{
if( !*str )
break;
*str = c;
++str;
}
//若字符串没有终止符,报错
assert( i < char_size );
//若char_size超出字符串的大小,则访问栈越界,报错
memset( str, 0, char_size - i + 1 );
return true;
}
int sstrcmp( const char *str1, const char *str2 )
{
//比较每个对应位置的字符,先转为unsigned char
while( *str1 && *str2 )
{
if( (unsigned char)*str1 < (unsigned char)*str2 )
return -1;
if( (unsigned char)*str1 > (unsigned char)*str2 )
return 1;
++str1;
++str2;
}
//若所有字符都相等,比较长度
if( !*str1 && !*str2 )
return 0;
if( !*str1 && *str2 )
return -1;
if( *str1 && !*str2 )
return 1;
}