1、题目
给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
比如 :
" I like http://hi.baidu.com/mianshiti " à "I like http://hi.baidu.com/mianshiti"。
2、代码
#include<stdio.h>
#include<string.h>
void removeExtraPalce(char * str);
main(){
char * str = " I like http://hi.baidu.com/mianshiti ";
removeExtraPalce(str);
return 0;
}
void removeExtraPalce(char * str)
{
int i,count=0;
int length =strlen(str);
bool begin;
if(str[0] != ' '){
begin=true;
}else{
begin=false;
}
printf("[");
for(i=0;i<length;i++){
//去掉字符串头部空格
if(str[i]==' ' && !begin){
if(i<length-1 && str[i+1] !=' '){
begin=true;
}
continue;
}
if(begin){
if(str[i] == ' '){
if(i<length-1 && str[i+1] !=' '){
//只输出中间的一个空格
printf("%c",str[i]);
count=0;
}
count++;
continue;
}
}
printf("%c",str[i]);
}
printf("]\n");
}
3、结果
3.1 测试1
字符串:"I like http://hi.baidu.com/mianshiti"
运行结果:
3.2 测试2
字符串:" I like http://hi.baidu.com/mianshiti"
运行结果:
3.3 测试3
字符串:" I like http://hi.baidu.com/mianshiti"
运行结果:
3.4 测试4
字符串:" I like http://hi.baidu.com/mianshiti"
运行结果:
3.5 测试5
字符串:" I like http://hi.baidu.com/mianshiti "
运行结果: