Friday, June 5, 2015

C++ programs to return a position of agiven string without using inbuilt functions

/*-------------------------------------------------------------------------------------------------------------------------------
Author: Sujith
Program: Write C++ programs to return a position of agiven string without using
inbuilt functions
Prog Name: posstr.cpp
Date: 21-04-2015
---------------------------------------------------------------------------------------------------------------------------------*/
#include<iostream>
using namespace std;
int strpos(char str1[],char str2[]);
main()
{
     char str1[25],str2[25];
     int len1,len2,rt;
     system("clear");
     cout<<"Enter the first string: \n";
     cin>>str1;
     cout<<"Enter the string to be searched: \n";
    cin>>str2;
    rt=strpos(str1,str2);
      if(rt==-1) {
      cout<<"The character doesnt exists\n";
      }else{
      cout<< "Starting position exists from: "<< rt<<endl;
     }
}
int strpos(char str1[],char str2[])
{
    int j1,j2,i;
    int len1,len2;
    len1=strlen(str1)-1;
    len2=strlen(str2)-1;
        for(i=0;i+len2<=len1;i++){
              for(j1=i,j2=0;j2<=len2 && str1[j1]==str2[j2];j1++,j2++){
                 if(j2==len2){
                   return i;
                 }
               }
          }
return -1;
}


Output:
[141740@localhost C++]$ g++ posstr.cpp
[141740@localhost C++]$ ./a.out
Enter the first string:
HappyBirthday
Enter the string to be searched:
Birthday
Starting position exists from: 5
[141740@localhost C++]$

No comments:

Post a Comment