给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个

给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。

转载地址: https://blog.csdn.net/sinat_21903855/article/details/48267699

#include <stdio.h>
#include <ctype.h>
#include <iostream>
char* Remove_extra_space(char* str)
{
    if (NULL == str){
        return NULL;
    }

    int newStart = 0;
    bool Prespace = true;

    char *ptr = str;

    int i = 0;

    while (ptr[i] != '\0')
    {
        if (ptr[i] != ' '){
            ptr[newStart++] = str[i];
            Prespace = false;
        }
        else if (ptr[i] == ' ' && Prespace == false){
            ptr[newStart++] = str[i];
            Prespace = true;
        }
        //去除标点符号前的字符
        if (ispunct(ptr[newStart - 1]) && ptr[newStart - 2] == ' '){
            ptr[newStart - 2] = str[i];
            newStart--;
        }
        i++;
    }

    newStart--;
    if (ptr[newStart] == ' '){
        ptr[newStart] = '\0';
    }
    else{
        ptr[newStart + 1] = '\0';
    }
    return ptr;

}

int main(int argc, char* argv[])
{
    char str[] = "You konw  ,  I    love  you  !  ";
    char* temp = Remove_extra_space(str);

    printf("%s\n", temp);
    return 0;
}
发布了38 篇原创文章 · 获赞 29 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/ruotianxia/article/details/79703526
今日推荐