C语言写的trim()函数
时间:2010-08-19 来源:juexun
作者:终南 <[email protected]>
C语言的标准库中缺少对字符串进行操作的trim()函数,使用起来有些不便,可以使用利用 strlen 和 isspace 函数以及指针来自己写一个。
1、strlen 函数
原型:extern int strlen(char *s);
用法:#include 功能:计算字符串s的长度 说明:返回s的长度,不包括结束符NULL。 2、isspace 函数 原型:extern int isspace(int c); 用法:#include 功能:判断字符c是否为空白符 说明:当c为空白符时,返回非零值,否则返回零。
空白符指空格、水平制表、垂直制表、换页、回车和换行符。 3、trim 函数 #include
#include char *trim(char *str)
{
char *p = str;
char *p1;
if(p)
{
p1 = p + strlen(str) - 1;
while(*p && isspace(*p)) p++;
while(p1 > p && isspace(*p1)) *p1-- = '\0';
}
return p;
} 4、应用举例 int main()
{
int i = 0;
char strs[][128] = {
NULL,
"",
" ",
"hello world",
" hello",
"hello world ",
" hello world ",
"\t\n\thello world ",
"END"
};
do
{
printf("trim(\"%s\")=%s.\n", strs[i], trim(strs[i]));
}while(strcmp(strs[i++], "END")); return 0;
}
文章出处:飞诺网(www.firnow.com):http://dev.firnow.com/course/3_program/c++/cppjs/20090207/154896.html
用法:#include 功能:计算字符串s的长度 说明:返回s的长度,不包括结束符NULL。 2、isspace 函数 原型:extern int isspace(int c); 用法:#include 功能:判断字符c是否为空白符 说明:当c为空白符时,返回非零值,否则返回零。
空白符指空格、水平制表、垂直制表、换页、回车和换行符。 3、trim 函数 #include
#include char *trim(char *str)
{
char *p = str;
char *p1;
if(p)
{
p1 = p + strlen(str) - 1;
while(*p && isspace(*p)) p++;
while(p1 > p && isspace(*p1)) *p1-- = '\0';
}
return p;
} 4、应用举例 int main()
{
int i = 0;
char strs[][128] = {
NULL,
"",
" ",
"hello world",
" hello",
"hello world ",
" hello world ",
"\t\n\thello world ",
"END"
};
do
{
printf("trim(\"%s\")=%s.\n", strs[i], trim(strs[i]));
}while(strcmp(strs[i++], "END")); return 0;
}
文章出处:飞诺网(www.firnow.com):http://dev.firnow.com/course/3_program/c++/cppjs/20090207/154896.html
相关阅读 更多 +