Answer to Question #204941 in C for Ali khan

Question #204941

Write a program that replaces two or more consecutive blanks in a string by a single 

blank. For example, if the input is Grim return to the planet of apes!! 

 the output should be Grim return to the planet of apes!!.


1
Expert's answer
2021-06-11T00:09:46-0400
#include <stdio.h>
#include <ctype.h>

char* remove_spaces(char* str) {
    char* p = str;
    char* q = str;
    int has_space = 0;

    while (*p) {
        if (isspace(*p)) {
            if (!has_space) {
                *q = *p;
                q++;
                has_space = 1;
            }
        }
        else {
            *q = *p;
            q++;
            has_space = 0;
        }
        p++;
    }
    *q = '\0';
    return str;
}

int main()
{
    char buf[1024];

    printf("Enter a string: ");
    gets(buf);
    remove_spaces(buf);
    printf("Clean string is:\n##%s##\n", buf);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS