kaya kaya - 1 month ago 5
C Question

To print only the first occurence of a substring in c

I am new to C. I have a code like this

#include <stdio.h>
#include <string.h>

int i = 0;
int main()
{
char text[] = "..... $it is beautiful : $yes you are correct....";
char * sub = "$";
char * ret = strstr(text, sub);

if (ret != NULL)
{
printf("the statement is : %s", ret);
}
}


I would like to print only this part of the code:
$it is beautiful
.
Is there any way to print only that statement? Let us assume that this a part of a full body text, so any idea other than using the
strlen
?
The print should not occur when the second
$
appears.This is the basic requirement for me

Answer

This should work.

 #include <stdio.h>
 #include <string.h>

 int i=0;
 int main()
{
    char text[] = "..... $it is beautiful : $yes you are correct....";
    char* sub = "$";
    char* ret = strstr(text,sub);
    char *out = malloc(strlen(text)+1); //To make the solution generic

    if (ret!=NULL )
     {
         sscanf(ret, "$%[^$^:]", out);
         printf("the statement is : [%s] \n",out );
     }

     free(out);
}
Comments