1. 程式人生 > >刪除字串中的空格-筆試題目

刪除字串中的空格-筆試題目

題目:給定一個字串,要求去掉字串首部以及尾部的空殼,字串中間的空格出現連續的只保留一個,比如 “ 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;

}

這裡沒有考慮時間、空間複雜度,僅僅是演算法實現,如果大家有更好的想法,歡迎留言