Function below gives checks if the given sub string exists in the target string and prints the index of sub string.
//Check if the given sub string exists in the string
#include <iostream>
using namespace std; bool CheckIfSubStringMatches(char * pStr, char * pSubStr) { while( ('\0' != *pSubStr) && ('\0' != *pStr) ) { if( *pSubStr != *pStr ) break; pSubStr++; pStr++; } if( '\0' == *pSubStr ) { return true; } return false; } void SearchSubstring( char* pBigString, char* pSubstring) { if( NULL == pBigString ) { cout<< "Invalid string entered. None found" << endl; return; } if( NULL == pSubstring ) { cout << "Invalid sub string to search." << endl; return; } if( strlen(pBigString) < strlen(pSubstring) ) { cout << "None found " << endl; return; } char * pStr = pBigString; char * pSubStr = pSubstring; int index = 0; while( '\0' != *pStr ) { if( *pStr == *pSubStr) { if( CheckIfSubStringMatches(++pStr, ++pSubStr) ) { cout << "Found SubString at Index = " << index << endl; return; } pSubStr = pSubstring; } else { pStr++; } index++; } cout << "None found " << endl; } int _tmain(int argc, _TCHAR* argv[]) { char myStr[4][5] = {{"This"}, {"put."}, {"xxxx"}, {"g I "} }; char * string = "This is the string I wanted to input."; for( int ctr = 0; ctr < 4; ctr++ ) { SearchSubstring( string, myStr[ctr] ); } return 0; } |
The output of code above is given below
Found SubString at Index = 0
Found SubString at Index = 33 None found Found SubString at Index = 17 |
No comments:
Post a Comment