How to resolve the algorithm String matching step by step in the C++ programming language
How to resolve the algorithm String matching step by step in the C++ programming language
Table of Contents
Problem Statement
Given two strings, demonstrate the following three types of string matching:
Optional requirements:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm String matching step by step in the C++ programming language
String Comparison:
-
s1.compare(0, s3.size(), s3) == 0;
checks if the firsts3.size()
characters ofs1
starting from index 0 are equal tos3
. It returnstrue
if they are equal, andfalse
otherwise. In this case, it checks if "abc" is equal to "ab", which isfalse
. -
s1.compare(s1.size() - s3.size(), s3.size(), s3) == 0;
checks if the lasts3.size()
characters ofs1
are equal tos3
. It returnsfalse
because "d" is not equal to "ab".
String Search:
-
s1.find(s2)
searches for the first occurrence ofs2
ins1
. If not found, it returnsstring::npos
, which is -1. In this case, it returns -1 because "abab" is not found in "abcd". -
s2.find(s3)
searches for the first occurrence ofs3
ins2
. If not found, it returnsstring::npos
. In this case, it returns 0 because "ab" is found at index 0 of "abab". -
loc = s2.find(s3, loc + 1)
searches for the first occurrence ofs3
ins2
starting from indexloc + 1
. It returnsstring::npos
if not found. In this case, it setsloc
to 0 and then finds the second occurrence of "ab" in "abab" at index 2.
Source code in the cpp programming language
#include <string>
using namespace std;
string s1="abcd";
string s2="abab";
string s3="ab";
//Beginning
s1.compare(0,s3.size(),s3)==0;
//End
s1.compare(s1.size()-s3.size(),s3.size(),s3)==0;
//Anywhere
s1.find(s2)//returns string::npos
int loc=s2.find(s3)//returns 0
loc=s2.find(s3,loc+1)//returns 2
You may also check:How to resolve the algorithm Poker hand analyser step by step in the Rust programming language
You may also check:How to resolve the algorithm Chowla numbers step by step in the Swift programming language
You may also check:How to resolve the algorithm Create an HTML table step by step in the Lua programming language
You may also check:How to resolve the algorithm Pythagorean triples step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Ordered words step by step in the CLU programming language