r/C_Homework • u/Casual_Browsing_ • Mar 03 '17
Convert String Array to Lowercase
Hi all! Hope you're all well! I have a quick question about a problem I'm having that I'm really getting a bit stuck on. I have to code a program that reads the words in a file, and outputs all the words in the file that end with ed to the console window. I've got the file to print all the words that end in ed. What I've realised is that it won't do the same for words that end in ED, Ed, or eD. I understand why this won't work. I could add other statement that outputs words that end in ED etc also; however, I was wondering if I could convert the words in the file to all lowercase first, then search for ed as this would be a better solution. I included a function that should lower the case of the array but it doesn't seem to work when I test. Anyone have any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Max_Lines 1000
#define Max_Length 500
int read_file( const char *filename, char* word_array[] );
void lower_string(char word_array[]);
int main( void )
{
int i, j;
int length;
char filename[ 300 ];
char* word_array[ Max_Lines ];
int opened = 0;
while ( opened != 1 ){
printf( "Please enter the file name you wish to search:\n" );
scanf("%s",filename);
if ( -1 == (j = read_file( filename, word_array ) ) ){
printf( "The file name entered could not be opened.\n" );
return 0;
}
else
{
opened = 1;
}
}
lower_string( word_array );
printf( "\nThe words ending in \"ed\" are as follows:\n" );
for ( i = 0; i <= j; i++ ) {
length = strlen( &word_array[ i ][ 0 ] );
if ( strcmp( &word_array[ i ][ length - 2 ], "ed" ) == 0 ) {
printf( "%s\n", &word_array[ i ][ 0 ] );
}
}
return 0;
}
void lower_string(char word_array[]) {
int c = 0;
while (word_array[c] != '\0') {
if (word_array[c] >= 'A' && word_array[c] <= 'Z') {
word_array[c] = word_array[c] + 32;
}
c++;
}
}
int read_file( const char *filename, char* word_array[] ){
char buffer[ Max_Length ];
int i = 0, length;
FILE * filePtr;
filePtr = fopen( filename, "r" );
if (!filePtr) {
return -1;
}
while ( !feof( filePtr ) ){
fscanf( filePtr, "%s", buffer );
length = strlen( buffer );
word_array[ i ] = ( char* )malloc( length + 1 );
strcpy( word_array[ i ], buffer );
++i;
}
fclose( filePtr );
return i;
}
View all comments
Show parent comment
2
u/jedwardsol Mar 03 '17
In read_file you set up word_array to be an array of strings.
You need to pass these strings individually to lower_string.
Your original lower_string is correct ... it will lower case a string. Leave it as it is.
Using j (which would be better called
numberOfLines) and lower_string, you can lower case each individual string in word_array