Following on from my previous question, it now appears that my code only outputs the first occurrence of cArray from cInput. Is there a way to get strstr to return all of the occurrences instead of stopping the program at the first? Much appreciated.
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN 120
int main(){
char *cArray[MAX_STR_LEN] = {"example", "this"};
char cInput[MAX_STR_LEN] = "";
char cOutput[MAX_STR_LEN] = "";
printf("Type your message:\n");
for (int y=0; y<1; y++){
fgets(cInput, MAX_STR_LEN, stdin);
char * ptr = cInput;
while((ptr=strstr(ptr, *cArray)) != NULL){
strncpy(cOutput, ptr, strlen(*cArray));
printf("Initialised string array:\n%s\n", cOutput);
ptr++;
}
}
}
Output:
Type your message:
this is an example
Initialised string array:
example
Program ended with exit code: 0
Edited code:
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN 120
int main() {
char *cArray[MAX_STR_LEN] = { "example", "this", "is", "an" };
char cInput[MAX_STR_LEN] = { 0 };
int y = 0;
printf("Type your message:\n");
fgets(cInput, MAX_STR_LEN, stdin);
cInput[strlen(cInput) - 1] = 0; /* strip newline from input */
printf("\nInitialised string array:\n");
while (cArray[y])
{
char * ptr = cInput;
while ((ptr = strstr(ptr, cArray[y])) != NULL)
{
char *ep = strchr (ptr, ' ');
if (ep) *ep = 0; /* null-terminate at space */
printf("%s\n", ptr++);
if (ep) *ep = ' '; /* put the space back */
}
y++;
}
return 0;
}
New output:
Type your message:
this is an example
Initialised string array:
example
this
is
is
an
Program ended with exit code: 0