Home > Software engineering >  What is the effective way to replace all occurrences of a character with every character in the alph
What is the effective way to replace all occurrences of a character with every character in the alph

Time:06-06

What is the effective way to replace all occurrences of a character with every character in the alphabet in std::string?

##include <algorithm>
#include <string>
using namespace std;

void some_func() {
string s = "example *trin*";
string letters = "abcdefghijklmnopqrstuvwxyz";
// replace all '*' to 'letter of alphabet'
for (int i = 0; i < 25; i  )
{
    //replace letter * with a letter in string which is moved  1 each loop
    replace(s.begin(), s.end(), '*', letters.at(i));

    i  ;
    cout << s;

}

how can i get this to work?

CodePudding user response:

You can just have a function:

  • receiving the string you want to operate on, and the character you want to replace, and
  • returning a list of strings with the new strings, once the replacement has been done;
  • for every letter in the alphabet, you could check if it is in the input string and, in that case, create a copy of the input string, do the replacement using std::replace, and add it to the return list.

[Demo]

#include <algorithm>  // replace
#include <fmt/ranges.h>
#include <string>
#include <string_view>
#include <vector>

std::vector<std::string> replace(const std::string& s, const char c) {
    std::string_view alphabet{"abcdefghijklmnopqrstuvwxyz"};
    std::vector<std::string> ret{};
    for (const char l : alphabet) {
        if (s.find(c) != std::string::npos) {
            std::string t{s};
            std::ranges::replace(t, c, l);
            ret.emplace_back(std::move(t));
        }
    }
    return ret;
}

int main() {
    std::string s{"occurrences"};
    fmt::print("Replace '{}': {}\n", 'c', replace(s, 'c'));
    fmt::print("Replace '{}': {}\n", 'z', replace(s, 'z'));
}

// Outputs:
//
//   Replace 'c': ["oaaurrenaes", "obburrenbes", "oddurrendes"...]
//   Replace 'z': []

Edit: update on your comment below.

however if I wanted to replace 1 character at a time for example in occurrences there are multiple "C" if i only wanted to replace 1 of them then run all outcomes of that then move onto the next "C" and replace all of them and so on, how could that be done?

In that case, you'd need to iterate over your input string, doing the replacement to one char at a time, and adding each of those new strings to the list you want to return.

[Demo]

    for (const char l : alphabet) {
        if (s.find(c) != std::string::npos) {
            for (size_t i{0}; i < s.size();   i) {
                if (s[i] == c) {
                    std::string t{s};
                    t[i] = l;
                    ret.emplace_back(std::move(t));
                }
            }
        }
    }

// Outputs:
//
//   Replace 'c': ["oacurrences", "ocaurrences", "occurrenaes"...]
//   Replace 'z': []
  • Related