#include <iostream>
using namespace std;
const char NULL_TERMINATED = '\0';
const int ONE_ELEMENT = 1;
//删除字符串两端的所有空格
char *my_trim( char *str )
{
if (NULL == str)
{
throw;
}
char *const address = str;
//跳过左端空格
while (NULL_TERMINATED != *str && isspace( *str ))
{
++str;
}
char *const new_address = str; //保存起来
//str继续前进直到指向串结束符的前一个字符
while (NULL_TERMINATED != *(str + ONE_ELEMENT))
{
++str;
}
while (new_address != str && isspace( *str ))
{
--str;
}
*(str + ONE_ELEMENT) = NULL_TERMINATED; //新的串结束位置
str = new_address;
return str;
}
int main(int argc,char*argv[])
{
char buf[] = " ok2002.com ";
char *p = my_trim( buf );
cout << p << endl;
cout << strlen( p ) << endl;
system( "PAUSE" );
return EXIT_SUCCESS;
}
/*----
ok2002.com
ok2002.com
请按任意键继续. . .
-----------------------*/
/*-------------------------------------
正确用法:
char buf[] = " ok2002.com ";
char *p = my_trim( buf );
cout << p << endl;
cout << strlen( p ) << endl;
不正确用法:
cout << buf << endl;
cout << strlen( buf ) << endl;
因为仅仅改变指针指向,没有作删除及移动字符等操作,结果提高了效率
---------------------------*/
trim()函数:仅仅改变指针指向,没有删除及移动字符,提高了效率
最新推荐文章于 2021-05-17 05:25:18 发布