CBSE Class 12 - Computer Science - C++ Practical String Processing Snippet-11 Sub-String Handling (#cbseNotes)

C++ Practical
String Processing Snippet-11
Sub-String Handling 

CBSE Class 12 - Computer Science - C++ Practical String Processing Snippet-11 Sub-String Handling (#cbseNotes)

Question: Write a substr() that will scan a string for the occurrence of a given sub-string
The prototype of the function would be:
    char* substr(char* str1, char* str2);
The function should return a pointer to the element in str1 where str2 begins.
If str2 does not occur in string1 then substr() should return a NULL
 e.g. if str1 = "Ena Meena Deeka" and str2 = "Meena"
then substr() should return address of 'M' in str1
write main() that uses the function substr()

Answer:

// Question: Write a substr() that will scan a string for the occurence of a given sub-string
// The prototype of the function would be:
//   char* substr(char* str1, char* str2);
// The function should return a pointer to the element in str1 where str2 begins.
// If str2 does not occur in string1 then substr() should return a NULL
// e.g. if str1 = "Ena Meena Deeka" and str2 = "Meena"
// then substr() should return address of 'M' in str1
// write main() that uses the function substr()

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


char* substr(char* str1, char* str2);

int main()
{
 char a[100],b[40];
 char *loc;
 cout << "Enter the main string:";
 gets(a);
 
 cout << "Enter the search string:";
 gets(b);
 
 loc = substr(a,b);
 
 if(loc == NULL)
     cout << "\nNot found";
 else
  cout << "Found at location " << loc;
 
 return(0);
}

char* substr(char a[],char b[])
{
 int i,j,first;
 i=0,j=0;
 while(a[i]!=' ')
 {
  while(a[i]!=b[0] && a[i]!='\0')
     i++;
  if(a[i] =='\0')
     return NULL;     //search can not continue

  first = i;
  while(a[i]==b[j] && a[i]!='\0' && b[j]!='\0')
  {
      i++;
      j++;
  }
  if(b[j]=='\0')
      return(&a[first]);
  if(a[i]=='\0')
      return(NULL);

  i = first + 1;
  j = 0;
 }
}

Output:
CBSE Class 12 - Computer Science - C++ Practical String Processing Snippet-11 Sub-String Handling (#cbseNotes)

Comments