tools.h:
# ifndef __TOOLS_H
# define __TOOLS_H
extern "C" char* ltrim(char* s);
extern "C" char* rtrim(char* s);
extern "C" char* alltrim(char* s);
或者
char* ltrim(char* s);
char* rtrim(char* s);
char* alltrim(char* s);
# endif
tools.cpp
#include "tools.h"
#include <cstdio>
#include <cstring>
/*去除字符串左边的空格*/
char* ltrim(char* s)
{
int i = 0, j = 0;
if(s == NULL)
return (char *)NULL;
while(' ' == s[i] || '\t' == s[i])
i++;
if(0 == i)
return s;
while('\0' != s[j + i])
{
s[j] = s[j + i];
j++;
}
s[j] = '\0';
return s;
}
/*去除字符串右边的空格*/
char* rtrim(char* s)
{
int i;
if(s == NULL)
return (char *)NULL;
for(i = strlen(s); i > 0; i--)
{
if(s[i - 1] == ' ' || s[i - 1] == '\t')
s[i - 1] = '\0';
else
break;
}
return s;
}
/*去除字符串两边的空格*/
char* alltrim(char* s)
{
ltrim(s);
rtrim(s);
return s;
}
测试demo.cpp
#include "tools.h"
#include <iostream>
using namespace std;
int main()
{
char szWaitTrim[50] = " abcdefghijklmnopqrstuvwxyz ";
char *lpAllTrimResult;
lpAllTrimResult = alltrim(szWaitTrim);
cout <<"lpAllTrimResult:" << lpAllTrimResult <<endl;
return 0;
}
编译运行及结果:
g++ -o demo demo.cpp tools.cpp
./demo
lpAllTrimResult:abcdefghijklmnopqrstuvwxyz
传递的是指针,原szWaitTrim内容已经变化了,如果还要对原数组进行其他操作的话需要注意。