w3resource

C++ String Exercises: Second occurrence of a string within another string

C++ String: Exercise-41 with Solution

Write a C++ program that finds the position of the second occurrence of a string in another string. If the Substring does not appear at least twice return -1.

Test Data:
("the qu qu", "qu") -> 7
("theququ", "qu") -> 5
("thequ", "qu") -> -1

Sample Solution:

C++ Code:

#include <bits/stdc++.h>

using namespace std;

int test(std::string text, std::string sstr)
{
	return text.find(sstr, text.find(sstr) + sstr.size());
}

int main()
{
	string text = "the qu qu";
	string sstr = "qu";
	cout << "String: " << text;
	cout << "\nSubstring: " << sstr;
	cout << "\nPosition of the second occurrence of the said substring: " << test(text, sstr);
	text = "theququ";
	sstr = "qu";
	cout << "\n\nString: " << text;
	cout << "\nSubstring: " << sstr;
	cout << "\nPosition of the second occurrence of the said substring: " << test(text, sstr);
	text = "thequ";
	sstr = "qu";
	cout << "\n\nString: " << text;
	cout << "\nSubstring: " << sstr;
	cout << "\nPosition of the second occurrence of the said substring: " << test(text, sstr);

}

Sample Output:

String: the qu qu
Substring: qu
Position of the second occurrence of the said substring: 7

String: theququ
Substring: qu
Position of the second occurrence of the said substring: 5

String: thequ
Substring: qu
Position of the second occurrence of the said substring: -1

Flowchart:

Flowchart: Second occurrence of a string within another string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Select lowercase characters from the other string.

Next C++ Exercise: Alternate the case of each letter in a string.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x