Reputation: 2093
My string:
std::string With_esc = "asd\b";
I want to convert it to a simple string "as" (apply the backspace character and forget it). Is there any way to do this in C++? It should look like this:
std::string With_esc = "asd\b";
std::string Without_esc = With_esc; //Here I should convert it
std::ofstream FWith_esc ("with");
std::ofstream FWithout_esc ("without");
FWithout_esc << Without_esc;
FWith_esc << With_esc;
Bash:
~ cat -e with
asd^H
~ cat -e without
as
Unfortunately I don't know how to convert it, so both files look exactly the same.
Upvotes: 1
Views: 2206
Reputation: 596397
Try something like this, if you don't want to use a regex:
std::string convertBackspaces(std:string str)
{
std::string::iterator iter = str.begin();
std::string::iterator end = str.end();
while (iter != end)
{
iter = std::find(iter, end, '\b');
if (iter == end) break;
if (iter == str.begin())
iter = str.erase(iter);
else
iter = str.erase(iter-1, iter+1);
end = str.end();
}
return str;
}
std::string Without_esc = convertBackspaces(With_esc);
Upvotes: 2
Reputation: 67090
Assuming you're lucky enough to use C++11 (otherwise adapt this code to your favorite regex engine):
string With_esc = R"asd\b";
string Without_esc = regex_replace(With_esc, regex(".\\b"), "");
As pointed out in comments this approach has following limitations:
"12\b\b"
you'll get "1\b"
. To handle this you need to loop until input and output (for regex_replace()
) are different (or maybe a better regex, I'm not such good with them).\b
as beginning of the string like in "\b123"
. To handle this you need a simple string replacement (using technique suggested by Giobunny) to remove \b
after a regex_replace
().UPDATE
As noted by Eric Finn this expression will also match multiple backspaces then "a\b\b\b"
will become "\b\b"
and then "\"
, that's obviously wrong. As he suggested a better regex should include check for "[^\b]\b"
too.
Upvotes: 4
Reputation: 96
You can replace the substring "\b"
with an empty string.
It's not the fastest/safest method but it will work,
you can follow.
Replace substring with another substring C++
Upvotes: 0