Hello everyone
I was requested to write a program which perceives
a string from the user and a small letter .the function should dynamically allocates new array of characters which contains all words in the string starting with the chosen letter(there is not different between small or capital letters) the function should return by pointer the size of array and returns the place of array in the memory.
for example the user typed the string "Hello World" and the chosen letter is w
so the array contains the word 'world' and its size is 1 hence there is only one row in the array
I tried to programming that but fortunately my code did not work.
I will be very thankful if someone can help
thanks,
so that is my code
Code:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define SIZE 20 //maximal size of string str
char **split(char letter, char *str, int *size_of_array);
void main()
{
char str, letter, **arr1;
int size_of_array;
printf("Please enter a string of worlds as you wish\n");
fgets(str, SIZE, stdin);
printf("%c", str[1]);
printf("Please enter a small letter as you wish\n");
scanf("%c", &letter);
_flushall();
arr1 = split(letter, str, &size_of_array);
printf("The size of arr is %d", size_of_array);
for (int i = 0; i < size_of_array; i++) {
for (int j = 0; arr1[i][j] != '\0'; j++)
printf("%c", arr1[i][j]);
printf("\n");
}
}
char **split(char letter, char *str, int *size_of_array)
{
char **arr;
int number_of_words = 0, i = 0, number_of_chars = 0, j = 0, k = 0, s = 0;
while (str[i] != '\0') {
if ((str[i] == ' '
&& (str[i + 1] == letter || str[i + 1] == tolower(letter)))
|| str[0] == letter) {
number_of_words++;
}
i++;
}
arr = (char **) malloc(sizeof(char *) * number_of_words);
i = 0;
while (str[i] != '\0') {
if (((str[i] == letter || str[i] == tolower(letter)) && str[i - 1] == ' ')
|| str[0] == letter) {
while (str[i] != ' ') {
arr[j] = (char **) malloc(sizeof(char *) * (number_of_chars++));
i++;
}
for (k = 0; k < number_of_chars; k++) {
arr[j][k] = str[s];
s++;
}
}
arr = (char **) realloc(arr[j], sizeof(char *) * number_of_chars);
i++;
j++;
}
*size_of_array = number_of_words;
return arr;
}