// delete the blank.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> char MyArray[] = " I XX abcd, abcd is just a bold shit"; char *myMemCpy(char *Dest, const char *Src) { assert(Dest != NULL); assert(Src != NULL); while(*Src != '\0') { *Dest++ = *Src++; } return Dest; } void deleteBlank(char *pArray) { char delim[] = " "; char *pCurWord = NULL; char *pCurPos = &pArray[0]; pCurWord = strtok(pArray, delim); while (pCurWord != NULL) { pCurPos = myMemCpy(pCurPos, pCurWord); *pCurPos = ' '; pCurPos++; pCurWord = strtok(NULL, delim); } pCurPos--; *pCurPos = '\0'; } int _tmain(int argc, _TCHAR* argv[]) { deleteBlank(MyArray); printf("%s\n", MyArray); return 0; }
另外从网上参考了另一个算法,感觉更加简洁 转自出处
#include<stdio.h> #include<string.h> #include<stdlib.h> #define SPACE ' ' main() { char string[100], *blank, *start; int length, c = 0, d = 0; printf("Enter a string\n"); gets(string); length = strlen(string); blank = string; start = (char*)malloc(length+1); if ( start == NULL ) exit(EXIT_FAILURE); while(*(blank+c)) { if ( *(blank+c) == SPACE && *(blank+c+1) == SPACE ) {} else { *(start+d) = *(blank+c); d++; } c++; } *(start+d)='\0'; printf("%s\n", start); free(start); return 0;
编写代码实现删除一个字符串中连续出现超过一次的空格
最新推荐文章于 2021-09-03 11:23:57 发布