This code is supposed to strip blanks in an array if any exist to the right of a non-blank, but leave the rest of the string as-is. Pretend input may or may not have blanks to the right and you want to lop them off if there, and leave the remaining string. For instance, if you enter, "abc 123 " the program *should print, "abc 123". (Notice the strlen of the first string is 10, and the second is 7, and the spaces are removed.)
My problem is how to get the blanks out! I've tried to add a null terminator into the blank spot, and then test if a null terminator or valid character exists. If either of those are true, the for loop should exit, leaving any blank spaces to the right of a non-blank position...
But it doesn't work. It just returns the whole string. I'm thinking this line, for(k=len; k=0; k -= 1) is causing the problem... I'll try this, for(k=len; line[k] != '\0'; k -= 1) ... but I just came up with that on the subway... so it hasn't been debugged.
Also, I'm wondering if there's a better way of removing a blank than adding a '\0'.... hurmph...
// strip.c
#include <string.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int k, len;
char line[100];
char *pt;
pt = line;
gets(line);
len = strlen(line); // figure out length of string
for(k=len; k=0; k -= 1) // for loop starts at right of array
{
if(isspace(*(line + k)) != 0 )
*(line + k)='\0'; // if blank add null terminator
else
k=0;
//if( (*(line + k)) == '\0' || isalnum(*(line + k) != 0 )) k = -1; // if '\0' or alnum exit
}
printf("%s %d", line, strlen(line));
return 0;
}