Search
 
SCRIPT & CODE EXAMPLE
 

CPP

search substring cpp

// Rabin Karp Alogorithm - (search substring)

#include <iostream>
#include <string>

using namespace std;

#define ll long long
#define BASE 227
#define MOD 1000000007

ll hhash(string s, ll l = -1) {
	if (l == -1)
		l = s.size();
    ll h = 0;
	for (ll i = 0; i < l; i++)
    	h = (h * BASE + s[i]) % MOD;
    return h;
}

ll rabin_karp(string s, string t) {
    ll h1 = hhash(t), h2 = hhash(s, t.size());

    if (h1 == h2)
    	return 0;

    ll power = 1;
    for (ll i = 0; i < t.size(); i++)
    	power = (power * BASE) % MOD;

   	for (ll i = t.size(); i < s.size(); i++) {
   		h2 = (h2*BASE + s[i]) % MOD;
        h2 = (h2 - (power * s[i-t.size()] % MOD) + MOD) % MOD;
    	if (h1 == h2)
        	return i - (t.size() - 1);
   	}

   	return -1;
}

int main() {
	string s, t;
    cin>>s>>t;

    ll ans = rabin_karp(s, t);
    if(ans == -1)
    	cout<<"String not found"<<endl;
    else
    	cout<<"String ""<<t<<"" found at position "<<ans<<endl;

   return 0;
}

//Time Complexity: O(n)
//Space Complexity: O(n)
Comment

find substring in string c++

std::string parentstring = "Hello Agnosticdev, I love Tutorials";
std::string substring = "Agnosticdev";
auto index = parentstring.find(substring);
Comment

PREVIOUS NEXT
Code Example
Cpp :: return array of string in function c++ 
Cpp :: char to string c++ 
Cpp :: c++ class template 
Cpp :: difference between --a and a-- c++ 
Cpp :: c++ remove chars from string 
Cpp :: Youtube backlink generator tool 
Cpp :: how to make a square root function in c++ without stl 
Cpp :: find function in c++ 
Cpp :: char to int in c++ 
Cpp :: what do you mean by smallest anagram of a string 
Cpp :: c++ vector 
Cpp :: c++ find index of all occurrences in string 
Cpp :: toString method in c++ using sstream 
Cpp :: rock paper scissor c++ 
Cpp :: loop c++ 
Cpp :: onoverlapbegin ue4 c++ 
Cpp :: program to swap max and min in matrix 
Cpp :: cpp vscode multipe compilation 
Cpp :: intlen in c++ 
Cpp :: c++ random int troll 
Cpp :: cin does not wait for input 
Cpp :: integer max value c++ 
Cpp :: Start mongodb community server 
Cpp :: how to convert char to int in c++ 
Cpp :: options select from array 
Cpp :: create vectors of vectors c++ 
Cpp :: memset c++ 
Cpp :: bitmap 
Cpp :: cuda shared array 
Cpp :: building native binary with il2cpp unity 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =