C++ Check Substring of a String
- by user69514
I'm trying to check whether or not the second argument in my program is a substring of the first argument. The problem is that it only work if the substring starts with the same letter of the string.
.i.e
Michigan - Mich (this works)
Michigan - Mi (this works)
Michigan - igan (this doesn't work)
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
bool my_strstr( string str, string sub ) {
bool flag = true;
int startPosition = -1;
char subStart = str.at(0);
char strStart;
//find starting position
for(int i=0; i<str.length(); i++){
if(str.at(i) == subStart){
startPosition = i;
break;
}
}
for(int i=0; i<sub.size(); i++){
if(sub.at(i) != str.at(startPosition)){
flag = false;
break;
}
startPosition++;
}
return flag;
}
int main(int argc, char **argv){
if (argc != 3) {
printf ("Usage: check <string one> <string two>\n");
}
string str1 = argv[1];
string str2 = argv[2];
bool result = my_strstr(str1, str2);
if(result == 1){
printf("%s is a substring of %s\n", argv[2], argv[1]);
}
else{
printf("%s is not a substring of %s\n", argv[2], argv[1]);
}
return 0;
}