字符串去除首尾和中间重复空格

题目

美团在线模拟笔试题,字符串去除首尾和中间重复空格

解析

是否是字符串开始位置的空格标志位,start
遇到空格的标志位,flag

代码实现

#include 
#include 
#include 

char* deleteBlank(char* sourcestring){
    char* newstring = sourcestring;
    char* tmp = sourcestring;
    int start = 1;
    int flag = 1;
    for (; *tmp != '\0'; tmp++){
        if (*tmp == ' '){
            flag = 0;
            continue;
        }
        else if (start == 1 || flag == 1){
            *newstring++ = *tmp;
            flag = 1;
            start = 0;
        }
        else if(flag == 0){
            flag = 1;
            *newstring++ = ' ';
            *newstring++ = *tmp;
        }
    }
    *newstring = '\0';
    return newstring;
}

int main(void){
    char sourceString[] = "  I love   meituan   ";
    deleteBlank(sourceString);
    printf("%s\n", sourceString);
    printf("%d\n", strlen(sourceString));
    system("pause");
    return 0;
}

你可能感兴趣的:(C语言学习笔记)