I am running into a wall here because I don't see how I can iterate over the string and use the tolower() function without severely breaking my dynamically allocating array. Any advice would be suggested.
while (fscanf(file, "%s", str) != EOF) {
//doubles the word_alloc/str_array if we have more words than allocated
if(ThreadData.word_count >= ThreadData.word_alloc) {
ThreadData.word_alloc *= 2;
ThreadData.str_array =(char **) realloc(ThreadData.str_array, sizeof(char*) * ThreadData.word_alloc);
}
ThreadData.str_array[ThreadData.word_count] = (char *) malloc(sizeof(char) * (strlen(str) 1));
strcpy(ThreadData.str_array[ThreadData.word_count], str);
ThreadData.word_count;
}
CodePudding user response:
It is helpful to have a utility function to lowercase/uppercase/titlecase/whatever you want to do to your string, such as:
#include <ctype.h>
char * lowercase( char * s )
{
for (char * p = s; *p; p)
{
*p = tolower( *p );
}
return s;
}
Now, since your data is an array of strings, just use the function on each string in your data. With the function defined as it is above, you can do it in-line with your copy:
ThreadData.str_array[ThreadData.word_count] = (char *) malloc(sizeof(char) * (strlen(str) 1));
lowercase(strcpy(ThreadData.str_array[ThreadData.word_count], str));
ThreadData.word_count;
Remember to keep a good reference handy:
https://en.cppreference.com/w/c
A very good one, but very technical. Takes some time to get used to reading it.https://cplusplus.com/reference/
Gets pooh-poohed all the time, but isn’t all that bad. Very much easier for the beginner to follow.
CodePudding user response:
alternative without using tolower library
If you want to convert a word from upper case to lower case, you can use the ASCII table.
Here my program to convert it !
main.h
#ifndef _HEADER_H_
#define _HEADER_H_
void fill_str(char*);
void convert_to_lower_case(char*);
#endif
main.c
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
int main(){
int size = 15; // Size of your string
char* str = (char*) malloc(sizeof(char) * size);
fill_str(str);
convert_to_lower_case(str);
printf("%s", str);
return 0;
}
void fill_str(char* str){
printf("Enter your word : ");
scanf("%s", str);
}
void convert_to_lower_case(char* str){
int i = 0;
while(str[i] != '\0'){
if( (int)str[i] >= 65 && (int)str[i] <= 90){ // We are verifying if the ascii code of a character is in upper case
int ascii = str[i] 32; // Example: ASCII code of "A" => 65 and "a" => 97. So 97 - 65 = 32;
str[i] = (char) ascii;
}
i ;
}
}