Learn Computer Science programming - C# and C++ Algorithms

 

Substring implmentation (substr)

Locates a sub string inside a given string. C++ implementation below.
Code
strsubstring.zip
File Size: 2281 kb
File Type: zip
Download File

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

char *StrSubstring (char strMain[], char strPattern[])
{
     char *start = &strMain[0];
     char *strPattern2, *strMain2;
    
     for (; *start != '%%CONTENT%%'; start++)
     {  // For each position in strMain string...
          strPattern2 = strPattern; // Prepare to check for pattern string there
          strMain2 = start;
          
          while(*strPattern2 != '%%CONTENT%%')
          { // Characters differ
                if(*strPattern2 != *strMain2)
                     break;
                strPattern2++;
                strMain2++;
          }
          
 // Found match
          if(*strPattern2 == '%%CONTENT%%')
                return start;
     }
     return NULL;
}

void main()
{
int x;
wcout <<  endl << "*** Substring implmentation ***" << endl;
wcout << "*************************************************" << endl;
char *charLocation = StrSubstring ("Tom Hanks","anks");
cout << "The location of the substring anks starts with the letter  " << *charLocation << endl;
cin >> x;
 }