Created
April 23, 2023 15:45
-
-
Save ItsBenyaamin/7a1bde353d7deb53058f1e2b00ea06d8 to your computer and use it in GitHub Desktop.
a program to find a start index of a word in a phrase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
string getStringFromInput(int length); | |
int searchForTheQuery(string totalPhrase, string queryPhrase); | |
int main() | |
{ | |
int n, m; | |
cout << "Please enter total length of string: "; | |
cin >> n; | |
cout << "Please enter length of query: "; | |
cin >> m; | |
string totalPhrase = getStringFromInput(n); | |
string queryPhrase = getStringFromInput(m); | |
int index = searchForTheQuery(totalPhrase, queryPhrase); | |
if(index != -1) { | |
cout << "Start index of query: " << index; | |
}else { | |
cout << "Index not found!"; | |
} | |
return 0; | |
} | |
string getStringFromInput(int length) { | |
string inputedString; | |
while(true) { | |
cout << "Please enter an string with length of " << length << ": "; | |
cin >> inputedString; | |
if(inputedString.size() == length) { | |
break; | |
}else { | |
cout << "Length of the inputed string must be " << length << "!" << endl; | |
} | |
} | |
return inputedString; | |
} | |
int searchForTheQuery(string totalPhrase, string queryPhrase) { | |
for(int i = 0; i < totalPhrase.size(); i++) { | |
char currentChar = totalPhrase[i]; | |
bool canQueryNextChar = i + 1 < totalPhrase.size(); | |
if(currentChar == queryPhrase[0] && canQueryNextChar && totalPhrase[i + 1] == queryPhrase[1]) { | |
bool found = true; | |
for(int j = 0; j < queryPhrase.size(); j++) { | |
if(totalPhrase[i + j] != queryPhrase[j]) { | |
found = false; | |
break; | |
} | |
} | |
if(found) { | |
return i; | |
} | |
} | |
} | |
return -1; // not founded | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment