Reputation: 1
im trying to make a function that removes spaces and tabs from a given string except for the first tab or space in the string. when im using my function it removes the spaces and tabs except for the first one but it also removes the first letter after the first space or tab. for example > "ad ad ad"> "ad dad" instead of "ad adad" why is that?
void RemoveSpacetab(char* source) {
char* i = source;
char* j = source;
int spcflg = 0;
while(*j != 0) {
*i = *j++;
if((*i != ' ') && (*i != '\t'))
i++;
if(((*i == ' ') || (*i == '\t')) && (spcflg == 0)) {
i++;
spcflg = 1;
}
}
*i = 0;
}
Upvotes: 0
Views: 84
Reputation: 4473
The problem caused by two if
statements one after the other. Your i
precedes j
when you detect a space for first time.
Explanation:
In first cycle the i
points to position 0 and j
too. The 'a'
at position 0 will be overwritten with itself then j
moves onwards to position 1
. Your first if
block finds out that the character at position 0 is not a space and not a tab, so moves the i
to position 1.
In second cycle the 'b'
will be overwritten with itself then j
moves to position 2 which is a space. The first if
finds out that 'b'
at position 1 is not a space and not a tab so moves the i
to position 2. Now the second if
finds out that the i
points to a space for first time and moves it to the position 3 while j
is still points to the position 2.
In third cycle the 'a'
at position 3 will be overwritten with the space at position 2 and j
catches up with i
.
A possible fix to your code:
#include <stdio.h>
void RemoveSpacetab(char* source) {
char* i = source;
char* j = source;
char spcflg = 0;
while(*j != 0) {
*i = *j++;
if(*i == ' ' || *i == '\t') {
if(!spcflg) {
i++;
spcflg = 1;
}
}
else {
i++;
}
}
*i = 0;
}
int main() {
char my_string[] = "ad ad ad";
RemoveSpacetab(my_string);
printf("%s\n", my_string);
return 0;
}
Upvotes: 1
Reputation: 2708
You will need to separate your source and destination arrays as they will become different lengths. You could find the starting position before copying characters like this, lets say you pass the source and the length of the source as char* source, int length
(you could also calculate the length of the source with strlen(source)
, then your function could look like this:
int i = 0;
char* dest = malloc(sizeof(char) * length);
// Increment i until not space to find starting point.
while (i < length && (source[i] == '\t' || source[i] == ' ')) i++;
int dest_size = 0;
while (i < length) {
if (source[i] != '\t' && source[i] != ' ') {
// Copy character if not space to dest array
dest[dest_size++] = source[i];
}
i++;
}
dest[dest_size++] = 0; // null terminator
// Feel free to realloc to the right length with
// realloc(dest, dest_size * sizeof(char))
return dest;
Upvotes: 1