Contact Learn C
Copy Program Share Program

Program 96:To split sentence for a given character

Program 96:
#include<stdio.h>
#include<string.h>
main()
{
    int i=0,j=0,k=0;
    char str1[100]={0},substr[100][100]={0},c;
    printf("Enter a sentence\n");
    gets(str1);
    printf("Enter a character to split\n");
    scanf("%c",&c);
    while(str1[k]!='\0')//for splitting sentence
    {
        j=0;
        while(str1[k]!=c&&str1[k]!='\0')
        {
            substr[i][j]=str1[k];
            k++;
            j++;
        }
        substr[i][j]='\0';
        i++;
        if(str1[k]!='\0')
        {
            k++;
        }        
    }
    int len=i;
    printf("\nWords after splitting sentence are:\n\n");
    for(i=0;i<len;i++)
    {
        printf("%s\n",substr[i]);
    } 
}
Explanation:
Here we need to split the entire sentence into parts wherever the character for which we wanted splitting occurs.For example: Lets take a sentence:
"This is Planet Earth" is the sentence we have.Now let the character for splitting sentence be space.In the example space occurred after "This","is","Planet","Earth"
So there are 4 words which are stored in 4 arrays.As "This" itself will take 1 full 1D array as for example
str1="This"
str2="is"
str3="Planet"
str4="Earth"
stored in 4 character arrays.As we don't know how many words will be created after splitting we cannot declare those many variables which is why we need to use 2D array to store words
So above example can be stored in
str[0]="This"
str[1]="is"
str[2]="Planet"
str[3]="Earth"
one variable will be enough to store all words.You might ask This is 1D array but where is 2D here?
If you see ,each character of string is stored in 1D array(as a string is nothing but a character array). For Example if you take
str[1]="This"
str[0][0]='T'
str[0][1]='h'
str[0][2]='i'
str[0][3]='s'
str[0][4]='\0'----representing end of string
This is how they are stored internally but while printing you can print them using "%s",str[0] which will print that entire array as %s indicates to print string till it find '\0' (End of String)

Now Lets come to our program:
  1. This program starts with initializing :
    • str1→ To store input from user
    • substrTo store output
  2. printf("Enter a sentence\n");
        gets(str1);
    Taking sentence from user
  3. printf("Enter a character to split\n");
        scanf("%c",&c);
    Taking character from user to split sentence 
  4. //Coming Soon remaining part
Output:

To split sentence for a given character

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide