Friday 16 March 2018

Extract substring from a given string until the specified character

This program reads a string and a character and displays part of the string up-to the specified character.
Example
Given string
welcome
Given character
c
OUTPUT
wel

//Program to extract a sub string up-to a specified character

#include<stdio.h>
#include<stdlib.h>

int main()
{
      int i=0;
      char s[100],c;

      printf("enter string\n");
      scanf("%s",s);
      printf("enter character ");
      scanf(" %c",&c);
     while (s[i]!='\0')
    {
           if (s[i]==c)
                   break;
   
           printf("%c",s[i]);
              i++;
      }

    return 0;
}






OUTPUT
Enter string
good_morning
Enter character_
good

Note: After reading a string, the following scanf() to read a character will not wait for input, since the newline(\n) character at the end of the string is taken as an input to that character.
Hence,write the scanf() function to read the character as scanf(" %c",&c); 
Note there is blank space before % symbol. 

No comments:

Post a Comment