----------------------------------------C---------------------------------------
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * trim(char * ptr)
{
int start,end,i;
if (ptr)
{
for(start=0; isspace(ptr[start]); start++)
;
for(end=strlen(ptr)-1; isspace(ptr[end]); end--)
;
for(i=start; i<=end; i++)
ptr[i-start]=ptr[i];
ptr[end-start+1]='\0';
return (ptr);
}
else
return NULL;
}
-------------------------------------C++-----------------------------------
#include <string>
using namespace std;
string trim(string &s)
{
const string &space =" \f\n\t\r\v" ;
string r=s.erase(s.find_last_not_of(space)+1);
return r.erase(0,r.find_first_not_of(space));
}
string ltrim(string &s)
{
const string &space =" \f\n\t\r\v" ;
return s.erase(0,s.find_first_not_of(space));
}
string rtrim(string &s)
{
const string &space =" \f\n\t\r\v" ;
return s.erase(s.find_last_not_of(space)+1);
}
字符串修剪
本文提供C和C++语言中去除字符串首尾空白字符的方法。C版本通过指针操作实现字符串的前后空白去除;C++版本则利用标准库函数实现字符串的左、右及两头空白去除。
811

被折叠的 条评论
为什么被折叠?



