The code is to search a word from the string entered. What optimizations can I do to my code and also any other(faster/req. less memory) way I can implement it.
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
bool possible(char str[], char str_part[]) {
int len_str = strlen(str);
int len_part = strlen(str_part);
if (len_str < len_part)
return false;
return true;
}
bool compare(char str[], char str_part[], int pos) {
int flag = 0;
for (int i = 0; i < strlen(str_part); ++i) {
if(str[i+pos] == str_part[i])
++flag;
}
if (flag == strlen(str_part))
return true;
return false;
}
int main(int argc, char* argv) {
char str[100];
cout << "enter the string";
gets(str);
char str_part[100];
cout << "enter the string to be searched";
gets(str_part);
bool check = possible(str, str_part);
if (check) {
for (int i = 0; i < strlen(str);++i ){
if(str[i] == str_part[0])
if(compare(str, str_part, i)) {
cout << "found it!!";
return 0;
}
}
}
cout << "got nothin";
return -1;
}
PS:I know about strlen() in for loop so leave that one :)
Aucun commentaire:
Enregistrer un commentaire