How to print only the first sentence in string [C]?

167 views Asked by At

Example:

void stringEvaluation(char *name){
    if (strstr(name, "Tall") != NULL)
        --here I would like to print only "John Doe"--

}

int main{
    char name[160 + 1];
    scanf("%[^\n]%*c", name);

    stringEvaluation(name);

return 0;
}

and this is the input

"John Doe (45). Black. Tall. Brown eyes"

3

There are 3 answers

0
BLUEPIXY On

Your request is unclear. For example, do as follows.

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

void stringEvaluation(const char *s){
    const char *p;

    if(s == NULL || *s == '\0'){
        puts("invalid format.");
        return ;
    }
    (p = strchr(s, '(')) || (p = strchr(s, '.'));
    if(p == NULL){
        puts("invalid format.");
        return ;
    }
    //find end
    while(!isalpha((unsigned char)p[-1]))
        --p;
    while(s < p)
        putchar(*s++);
}

int main(void){
    char name[160 + 1] = "";
    scanf("%160[^\n]%*c", name);

    stringEvaluation(name);

    return 0;
}
0
MayurK On

I am using strtok() to get the name. Please note, this will work only if you have "()" in your string.

void stringEvaluation(char *name){
    if (strstr(name, "Tall") != NULL)
    {
        char *nameEnd = strtok(name, "("); //Returns address of '('
        if(NULL != nameEnd)
        {
            int nameLength = nameEnd - name - 1; // 1 for space after name.

            char *onlyName = malloc((nameLength + 1) * sizeof(char)); // 1 for terminating '\0'
            if(NULL != onlyName)
            {
                //Copy name part.
                strncpy(onlyName, name, nameLength);
                onlyName[nameLength] = '\0'; //Make onlyName a string

                printf("Name: [%s]\n", onlyName);

                free(onlyName);
                onlyName = NULL;
            }
        }
    }
}
0
Akshay Patole On

I have assumed that name will be at first place in your input string. Then following small logic will work for you.

void stringEvaluation(char *name){
    char *p;
    char OutPut[50]={0};
    if (strstr(name, "Tall") != NULL)
    {
        p = strstr(name," ");
        p++;
        p = strstr(p," ");
        strncpy(OutPut,name,(p-name));
        printf("name=%s\n",OutPut);
    }

}