arrays - Check a string in another string in C++ -
#include <iostream> #include <string> using namespace std; int main() { string str_1 = "gandalf"; string str_2 = "dal"; (int = 0; <= str_1.length() - 2; i++) (int j = 0; j <= str_2.length(); j++) { if (str_2[j] == str_1[i]) { if (str_2[j + 1] == str_1[i + 1]) { if (str_2[j + 2] == str_1[i + 2]) cout << "true"; } } } return 0; } i can if length of str_2 4 characters, program doesn't work. want program can work every length of string how?
the function find below reproduces behaviour of std::string::find (without starting position parameter). need to:
- loop through outer string, , @ each step:
- loop through second string checking each character.
- if of these fail, drop outer loop.
- if make way through inner loop, second string there, , return current position in outer loop.
- if run out of space in first string, skip rest.
hopefully comments make clear. include little utility function turn found position true/false, , tests.
#include <iomanip> #include <iostream> #include <string> std::string::size_type find(const std::string& s1, const std::string& s2) // return position of s2 within s1, // else npos if not present. { using size_type = std::string::size_type; size_type curpos = 0; size_type lim = s1.size(); size_type innerlim = s2.size(); (; curpos<lim; ++curpos) { // loop through s1 if (lim < curpos+innerlim) { break; // not enough space left } size_type innerpos = 0; for(; innerpos < innerlim // loop through s2, while matching && curpos + innerpos < lim && s1[innerpos+curpos] == s2[innerpos]; ++innerpos) ; // nothing in loop if (innerpos == innerlim) { // matched whole loop return curpos; } } return std::string::npos; // never matched } bool contains(const std::string& s1, const std::string& s2) { return find(s1, s2)!=std::string::npos; } int main() { std::cout << std::boolalpha << contains("abc", "") << '\n' // true << contains("abc", "abc") << '\n' // true << contains("abc", "bc") << '\n' // true << contains("abc", "abcd") << '\n' // false << contains("abc", "abd") << '\n' // false << contains("abc", "xyz") << '\n';// false } this more need, closely models "real" answer (use facilities language provides). plus makes not great homework answer, contains clues write homework answer.
Comments
Post a Comment