C++ Program to count operations to make filename valid

Suppose we have a string S with n letters. Amal is trying to send a file in the social network, but there is an unexpected problem. If the name of the file contains three or more "x" consecutively, the system considers that the file content does not correspond to the social network. We have the filename in S. We have to check whether the minimum number of characters to be removed S so that, the name does not contain "xxx" as a substring.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.



So, if the input of our problem is like S = "lkxxxiii", then the output will be 1, because we can make string "lkxxiii" which is valid.


To solve this, we will follow these steps −

c := 0
n := size of S
for initialize i := 0, when i < n - 2, update (increase i by 1), do:
   if substring of S of size 3, starting from index i to is same as "xxx", then:
      (increase c by 1)
return c


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(string S){
   int c = 0;
   int n = S.size();
   for (int i = 0; i < n - 2; i++){
      if (S.substr(i, 3) == "xxx")
   return c;
int main(){
   string S = "lkxxxiii";
   cout << solve(S) << endl;





Updated on: 08-Apr-2022


Kickstart Your Career

Get certified by completing the course

Get Started