Split a string using pointers

 

write a c program to split a string, using pointers.

input: contains a string of two names(first_name, last_name) separated by a 'space'.
output: print two strings, each with one name.

Sample input 1:
name( first_name<space>last_name): Graham Bell
Output 1:
first name: Graham
last name : Bell


Sample input 2:
name( first_name<space>last_name): GrahamBell
Output 2:
there is no space in the name.
exiting...


Program:

/* c program to split string into two using pointers */
#include<stdio.h>
#include<stdlib.h>
int main()
{
           char s[100];
           char ch;
           int i,j;
           char *ps,*pt;
           ps=s;
           pt=s;
           printf("name( first_name<space>last_name): ");
           scanf("%[^\n]",s);
           while((*ps)!=' '){
           if(*ps=='\0')                                                                         /* No space found till end of line */
              {
                  printf("there is no space in the name.\nexiting...");
                  exit(0);                                                                          /* exit from the program */
              }
           ps++;
           }
           *ps='\0';
           ++ps;
           printf("first name: %s",pt);
           printf("\nlast name : %s\n",ps);
           return 0;
}

No comments: