so I'm trying to create a program which looks at a string defined in main, and deletes any non-alphabetical characters (excluding \0). So far this is my code:
/* Write code to which considers the string currently saved
* in the 'name' array, removes all spaces and non-alphabetical
* chars from the string, and makes all alphabetical characters
* lower case. */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define NAMELEN 30
int main (void) {
char name[NAMELEN];
strcpy(name, " William B. Gates");
int i, length, check;
length = strlen(name);
for ( i = 0; i < length; i++ ) {
check = isalpha(name[i]);
if ( check == 0 ) {
for ( ; i < length; i++ ) {
name[i] = name[i+1];
}
}
}
printf("The length is %lu.\n", strlen(name));
printf("Name after compression: %s\n", name);
return EXIT_SUCCESS;
}
So for the test data, " William B. Gates", the output should be "WilliamBGates", unfortunately the output I'm getting is:
The length is 16.
Name after compression: William B. Gates
I think the space before William has been deleted, but I'm unable to tell. Thanks for any help!
This inner loop is wrong
It copies the string in itself excluding the first character and after that your program does nothing because i is already equal to length.
So the program only removes one non-alpha character from the string.
When you are going to traverse a string sequantially then there is no need to calculate its length. The program can be written simpler or at least you may use the approach that is demonstrated below. For example
The program output is