How to resolve the algorithm String matching step by step in the C++ programming language

Published on 7 June 2024 03:52 AM

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 first s3.size() characters of s1 starting from index 0 are equal to s3. It returns true if they are equal, and false otherwise. In this case, it checks if "abc" is equal to "ab", which is false.

  • s1.compare(s1.size() - s3.size(), s3.size(), s3) == 0; checks if the last s3.size() characters of s1 are equal to s3. It returns false because "d" is not equal to "ab".

String Search:

  • s1.find(s2) searches for the first occurrence of s2 in s1. If not found, it returns string::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 of s3 in s2. If not found, it returns string::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 of s3 in s2 starting from index loc + 1. It returns string::npos if not found. In this case, it sets loc 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