Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove redundant whitespace from string (in-place)

Tags:

c

pointers

Ok so i posted earlier about trying to (without any prebuilt functions) remove additional spaces so

"this is <insert many spaces!> a test" would return

"this is a test"

Remove spaces from a string, but not at the beginning or end

As it was homework i asked for no full solutions and some kind people provided me with the following

"If you need to do it in place, then create two pointers. One pointing to the character being read and one to the character being copied. When you meet an extra space, then adapt the 'write' pointer to point to the next non space character. Copy to the read position the character pointed by the write character. Then advance the read and write pointers to the character after the character being copied."

The problem is i now want to fully smash my computer in to pieces as i am sooooo irritated by it. I didnt realise at the time i couldnt utilise the char array so was using array indexes to do it, i thought i could suss how to get it to work but now i am just using pointers i am finding it very hard. I really need some help, not full solutions. So far this is what i am doing;

1)create a pointer called write, so i no where to write to

2)create a pointer called read so i no where to read from

(both of these pointers will now point to the first element of the char array)

while (read != '\0')
    if read == a space 
        add one to read
        if read equals a space now 
            add one to write
            while read != a space {
                 set write to = read
            }
                 add one to both read and write
    else 
        add one to read and write 
        write = read  
like image 562
leo Avatar asked Dec 01 '25 01:12

leo


1 Answers

Try just doing this yourself character by character on a piece of paper and work out what it is you are doing first, then translate that into code.

If you are still having trouble, try doing something simpler first, for example just copying a string character for character without worrying about the "remove duplicate spaces" part of it - just to make sure that you haven't made a silly mistake elsewhere.

like image 122
Justin Avatar answered Dec 03 '25 15:12

Justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!