问题描述:去除字符串首尾空格
方法一;自己实现
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char * delete_space(char src [])// 删除首尾空格
{
char *dec = src;
char *p1 = src ;
char *p2;
while( *p1 == ' '||*p1 = '\t')
{
*p1++;
}
p2 = p1;
while( *p2 )
{
p2++;
}
while( --p2 >= src && (*p2 == ' '&& *p2 =='\t'));
if(p2 >= p1)
{
*src++ = * p1++;
}
src = 0;
return src;
}
int main()
{
char str[] = " math is fun! ";
char src[20];
int i,j;
printf("%s",delete_space(str));
for(i = 0; i < strlen(str); i++)
{
if(!(str[i] == 32 && str[i+1] == 32))//空格为32
{
src[j++] == str[i];
}
}
printf("\n");
return 0;
}
方法二:利用系统自带函数实现
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line = " This is a test. ";
line.erase(0, line.find_first_not_of(" \t")); // 去掉头部空格
line.erase(line.find_last_not_of(" \t") + 1); // 去掉尾部空格
cout << "{"<< line << "}" << endl;
return 0;
}