The following program is supposed to return the length of a 'hidden' string within each of the sentences of another string, using pointers and avoiding as much as possible the use of []
as a means to access strings. We were instructed on how to declare the functions, hence their declarations are a given.
#include <stdio.h>
#include <stdlib.h>
int getHiddenString(const char * str1 , const char * str2);
int divideStringIntoSentences(char * string, char * sentences[]);
char* readLine();
int main()
{
char *ptrarr[20];
int i = 0;
printf ("Please enter a string:\n");
char *str1 = readLine();
printf ("Please enter a hidden string:\n");
char *str2 = readLine();
if (str2 == NULL) return EXIT_FAILURE;
int j = divideStringIntoSentences(str1, ptrarr);
for (; i <= j; i++)
printf ("Sentence %d contains hidden string prefix length %d\n", i,
getHiddenString(*(ptrarr + i), str2));
free (str1);
free (str2);
return 0;
}
int getHiddenString(const char * str1 , const char * str2)
{
int hidlen = 0;
for (; *str1 != '\0' && *str2 != '\0'; str1++)
if (*str1 == *str2)
{
hidlen++;
str2++;
}
return (hidlen);
}
char* readLine()
{
int capacity = 1, index = 0;
char c;
char *str1 = (char*) malloc(capacity * sizeof(char));
if (str1 == NULL) return NULL;
for (c = getchar(); c != '\n' && capacity <= 100; c = getchar())
{
if (index == capacity - 1)
{
str1 = (char*) realloc(str1, (++capacity) * 2 * sizeof(char));
if (str1 == NULL) return NULL;
capacity*=2;
}
*(str1 + index++) = c;
}
*(str1 + index) = '\0';
return str1;
}
int divideStringIntoSentences(char * string, char * sentences[])
{
int sentnum = 0;
*sentences = string;
for (; *string != '\0'; string++)
if (*string == '.')
{
*string = '\0';
*(++sentences) = (string + 1);
sentnum++;
}
return (sentnum);
}