String Question
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...
newbiecoder
Junior Poster in Training
60 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
>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 ;)
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
How I would do it:Create a temporary variable of the same length as the one were you want to delete the spaces from
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.
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!)
tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
Remember KISS principle: no need in temporary strings! ;)
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
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
tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
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.
jephthah
Posting Maven
2,587 posts since Feb 2008
Reputation Points: 2,143
Solved Threads: 179
>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;
}
;)
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348