Hi,
I want to write a code which takes an array of 20 characters and deletes all spaces between characters, it should leave only letters. For example:
input : d a n i w e b
I want to make it : daniweb

I wrote this code, but it didn't change anything:

#include <stdio.h>

 int main ()
 {
         int i;
         char a[21];



         gets(a);

         for(i = 0; i < 20; i++)
         {
                 if(a[i] == 8 || a[i] == 9)
                 {a[i]= a[i+1];
                 i--;}
                 else continue;
         }

         printf("%s", a);
         printf("\n");

         return 0;
 }

Can you help me with that? Thank you all...

Recommended Answers

All 6 Replies

>I wrote this code, but it didn't change anything
You can't compile this code, that's why it didn't change anything: the else alternative has no correspondent if! Didn't you see it?

What did you want to achieve with so strange a[i] == 8 || a[i] == 9 condition?

It's a very simple assignment. Please, think again then caome back with a proper code tag:
[code=c] source

[/code]

Or search DaniWeb more carefully: there are lots of right solutions of this assignment ;)

How I would do it:

  1. Create a temporary variable of the same length as the one were you want to delete the spaces from
  2. Use a for-loop to loop through the whole string where you want to delete the spaces from, every time you check whether the read character is a space or another character, when the character is a space, don't copy it to the temporary string, otherwise: copy it to the temporary string.
  3. Eventually you could use strcpy to copy the string without the spaces to the variable which was holding the string with the spaces (note that it will be overwritten then!)

Remember KISS principle: no need in temporary strings! ;)

commented: Keep It Simple Stupid!! You're right! +7

Remember KISS principle: no need in temporary strings! ;)

I thought that was the simplest way, however he could also just shift each character to the left if there's a space in between. Or do you know the 'ultimate' way? :P

Or do you know the 'ultimate' way?

i know the ultimate way

#include<jephthah.h>

newStr_ptr = removeSpacesAndCondense(myString);

it's non-standard and not very portable, but hey, it works on my machine.

commented: ROFL :P +7
commented: :D +10

>Or do you know the 'ultimate' way?
Why not?

char* condense(char* s)
{
    if (s) {
        char* p = s;
        char* q = s;
        /* (never write so:) */
        do if (*p != ' ')
           *q++ = *p;
        while (*p++);
    }
    return s;
}

;)

commented: that's a good way +9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.