How to find substring of a string in C++?

The easiest way to search for a word in a sentence including uppercase and lowercase characters is to first search for the indexes at which the first letter occurs and locate the word at each index separately.

char * Sentence; // Has a sentence “Happy Birthday to you”
char * word; // Has a word “Birthday”
int length; // length of word
//Step 1: Converting the First Letter of word into Upper or Lower case
int index = -1;
char Upper = 0, Lower = 0;
if (word[0] <= 90) {
  Lower = word[0] + 32;
} else {
  Upper = word[0] - 32;
}
int Indices[10];
for (int i = 0; i < 10; i++)
  Indices[i] = -1;
int I = 0;
for (int a = 0; sentence[a] != '\0'; a++) {
  if (sentence[a] == Upper || sentence[a] == Lower || sentence[a] ==
    word[0]) {
    index = a;
    Indices[I] = a;
    I++;
  }
}
//Step 2: Now For Each of these Index Positions, see if there is a match
I = 0;
while (Indices[I] != -1) {
  int indx = Indices[I];
  if (indx != -1) {
    indx++;
    int found = 1;
    for (int j = 1; j < length; j++) {
      if (sentence[indx] == word[j]) {
        indx++;
        found++;
      }
    }
    if (found == length) {
      return true;
    }
  }
  I++;
}
return false;
}

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.