Reputation: 1
I've been trying to make a function in C that takes a string as the input and then prints out a version of that string that only contains alpha characters.
#include <string.h>
#include <ctype.h>
char isAlpha(char charArr[]){
int i, j, stringLen, alphaLen;
stringLen = strlen(charArr);
char alphaArr[30];
for(i= 0; i < stringLen; i++){
if(isalpha(charArr[i]) != 0){
strcat(alphaArr, charArr[i]);
}
}
alphaLen = strlen(alphaArr);
for(j = 0; j < alphaLen; j++){
printf("%c", alphaArr[j]);
}
}
I've tried using the strcat()
function to add the non-alpha characters in a new variable, but nothing prints out once I run it in my main function.
Upvotes: -1
Views: 110
Reputation: 311088
This declaration with the magic number 30
char alphaArr[30];
declares an uninitialized character array.That is its content is indetermined.
The function strcat
is declared the following way
char *strcat(char * restrict s1, const char * restrict s2);
It expects two pointers to strings. So this call
strcat(alphaArr, charArr[i])
is invalid even if to ignore that the first argument points to an array with an indeterminate content (the first argument must be a pointer to a string) at least because the second argument has the integer type char
instead of a pointer to char
.
In any case there is no great sense to use the function strcat
to append one character to a character array. You could just use a separate index in the for loop for the destination array.
Moreover the function returns nothing though its return type is not void
.
And the function should do only one thing: either it should build a new string or it should only output alpha characters of the passed string.
And as the passed string is not changed within the function the parameter should be declared with qualifier const
.
Calling the function strlen
in any case is redundant. And calling the function for a character array that does not contain a string results in undefined behavior.
To output only alpha characters of a string the function can be defined the following way
void isAlpha( const char charArr[] )
{
for ( ; *charArr != '\0'; ++charArr )
{
if ( isalpha( ( unsigned char ) *charArr ) )
{
putchar( *charArr );
}
}
}
or the following way
FILE * isAlpha( const char charArr[], FILE *fp )
{
for ( ; *charArr != '\0'; ++charArr )
{
if ( isalpha( ( unsigned char ) *charArr ) )
{
putc( *charArr, fp );
}
}
return fp;
}
If you need to create a new array that contains a string of alpha characters of the source string then you need to allocate memory dynamically for the new character array that will contain a string and return a pointer to it from the function.
Upvotes: 3