-2

have string "cdfrcs". I want to get string *c*d*f*r*c*s(add stars before every symbol). How should I do it?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
YoungCoder
  • 3
  • 1
  • 3

2 Answers2

1

You can use regex_replace to add an asterisk before every character in an input string:

auto result = std::regex_replace(input, std::regex{"(.)"}, "*$1");

In the regex (.), the . matches every character, and () captures it in capture group 1.

The replacement string *$1 specifies that every captured character $1 is replaced with a preceding *.

Here's a demo.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • bro I used this way but the result is not desired. Why? #include #include #include using namespace std; int main() { string s; cin >> s; auto result = regex_replace(s, regex{ "(.)" }, "*$1"); cout << result; } – YoungCoder Apr 25 '21 at 20:26
  • @YoungCoder I don't know. Does `s` have spaces in it? How exactly does it not work? – cigien Apr 25 '21 at 20:32
  • *c*o*d*e*f*o*r*c*e*s is result. it does not move letters. adds only stars before every letter – YoungCoder Apr 25 '21 at 21:07
  • @YoungCoder We're not going to go off-site to test the program. You need to [edit] the question to explain clearly what the result should be. At the moment, it says "add stars before every symbol", and doesn't mention anything about "moving". – cigien Apr 25 '21 at 21:12
  • oh my mistake sorry for being confusing. From word "codeforces" I have to remove vowels and the rest of the letters must be in order but with stars in front of them. For instance, from "codeforces" we got "cdfrcs" and output must be with stars "cdfrcs" with stars in front of the letters. Thank you bro for your attention and time. Hope everything is clear now – YoungCoder Apr 25 '21 at 21:52
  • @YoungCoder Take a look at this [thread](https://stackoverflow.com/questions/50845519). You can combine the solution there along with the one in my answer to solve your problem. – cigien Apr 25 '21 at 22:15
0

If you don't want to use regex, the following works:

std::string a = "cdfrcs";
std::string b = "";
for(char c : a) {
    b += std::string("*") + c;
}
qz-
  • 674
  • 1
  • 4
  • 14