-1

We have a char. We need to replace all ab characters from our char with the letter c.

Example we have :

abracadabra

the output will be :

cracadcra

I tried to use replace() function from C++, but no success.

#include <iostream>
#include <cstring>
using namespace std;

int main()
  {
  string test;
  cin>>test;
  
  for(int i=0;i<(strlen(test)-1);i++)
  {
      if((test[i]=='a')&&(test[i+1]=='b')){
  test.replace( test[i], 'c' );
      test.replace( test[i+1] , ' ' );     
      }
  }
  cout << test << endl;
  return 0;
  }enter code here
crackaf
  • 492
  • 2
  • 11

3 Answers3

1

You can use C++11 regex:

#include <iostream>
#include <regex>
#include <string>

int main() {
  std::string str = "abracadabra";
  std::regex r("ab");
  std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}
dtell
  • 2,488
  • 1
  • 14
  • 29
0

Problem:

That is not the syntax of std::string::replace.

Solution:

As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c').

Or use regular expressions as dtell pointed.

Adittional information:

  1. using namespace std; is considered a bad practice (More info here).
  2. You should use std::string::size instead of strlen when you're working with std::string.
  3. To work with std::string you should use #include <string> instead of #include <cstring>.

Full code:

#include <iostream>

int main()
{
    std::string test;
    std::cin >> test;
    for(unsigned int i = 0; i < test.size() - 1; i++)
    {
        if((test[i]=='a') && (test[i+1]=='b'))
        {
            test.replace(i, 2, "c" );
        }
    }
    std::cout << test << std::endl;
    return 0;
}
Gary Strivin'
  • 908
  • 7
  • 20
0

The simplest thing you can do by using the standard library is first to find ab and then replace it. The example code I wrote is finding string ab unless there is None in the string and replacing it with c.

#include <iostream>
#include <string>

int main()
{
    std::string s = "abracadabra";
    int pos = -1;
    while ((pos = s.find("ab")) != -1)//finding the position of ab
        s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
    std::cout << s << std::endl;
    return 0;
}

//OUTPUT
cracadcra
crackaf
  • 492
  • 2
  • 11