题目:给定一个字符串,要求去掉字符串首部以及尾部的空壳,字符串中间的空格出现连续的只保留一个,比如 “ I love China ” 输出“I love China”
思路:首部空格,通过循环指针,并累加指针,使得指向第一个非空格字符串。
中间以及字符串最后空格,在字符串中,遇到一个空字符串时,将该指针复制给一个临时变量,同样循环该临时指针,一直到非空格指针时停止循环,并将该位置的上一个位置记录下来,但是要考虑到是否循环到字符串结束符 '\0' ,如果循环到改字符串时候则直接终止循环。
#include "stdafx.h"
#include <iostream>
using namespace std;
char* formatString(char *sourceString) {
char *p = sourceString;
char *end;
while (*p == ' '){
p++;
}
if (strlen(p) == 0)
return "";
int len = strlen(p);
end = p + len;
char *src = (char*)malloc(len+1);
int index = 0;
for (; p != end; ++p){
if (*p == ' '){
char *tmp = p;
while (*tmp == ' '){
tmp++;
}
if (*tmp == '\0')
break;
src[index++] = *(tmp-1);
p = tmp-1;
}
else src[index++] = *p;
}
src[index] = '\0';
return src;
}
int main(){
char *p = " sad dsa da dddds s ";
char *k = formatString(p);
cout << k;
}
这里没有考虑时间、空间复杂度,仅仅是算法实现,如果大家有更好的想法,欢迎留言