-4

I'm trying to write a function in C that removes all multiply spaces in a string.

For example:

"  some    random       string   " => "some random string"

I want a void function to get a string and without changing it just print it. I saw some previous threads about this question but didn't find the exact thing I need.

kicklog
  • 109
  • 2
  • 8
  • 1
    What have you tried? Why doesn't it work? – tkausl Nov 30 '17 at 10:23
  • 1
    Possible duplicate of [Removing Spaces from a String in C?](https://stackoverflow.com/questions/1726302/removing-spaces-from-a-string-in-c) – Dadep Nov 30 '17 at 10:23
  • You write "I'm trying to write a function...". So I suppose you have written a function that doesn't work for some reason. If you want help you need to [edit] your question and show your code _there_ – Jabberwocky Nov 30 '17 at 10:24
  • You also write: " I saw some previous threads about this question but didn't find the exact thing I need". Maybe you should tell us _what_ exact thing you need. – Jabberwocky Nov 30 '17 at 10:26
  • I'm sorry, but you are going to need to be clearer than that. 'get a string' from where? 'I want a void function' why this constraint? If the string getting fails, how is the fail to be notified to the caller? 'didn't find the exact thing I need' - see @MichaelWalz above. – Martin James Nov 30 '17 at 10:40

1 Answers1

0

Here is a starting example:

#include <stdio.h>

void print_str_but_no_mul_spaces(char* str)
{
    // eat pre-found whitespaces
    while(*str && *str == ' ')
        str++;
    while(*str)
    {
        // If this is not the prelast char AND
        // the next char is not a space OR
        // the current char is not a space AND next char is a space
        if(*(str + 1) != '\0' && (*(str + 1) != ' ' || (*str != ' ' && *(str + 1) == ' ')))
            putchar(*str);
        str++;
    }
}

int main(void)
{
    print_str_but_no_mul_spaces("  some    random       string   ");
    return 0;
}

which should inspire you to keep on, and make you remember to always show some research-effort before posting a question. Good luck!

gsamaras
  • 71,951
  • 46
  • 188
  • 305