I am trying to figure out how to delete one character at a time from a string, so that I can obtain all versions of the string with only one character missing at a time. This is what I am trying to make work, but to no avail.
for(int i = 0 ; i < s.length() ; i++){
tmp.erase(0, i);
std::cout << tmp << std::endl;
s.at(i)++;
}
It obviously works correctly for the first one, but then deletes the rest. JON should have an expected output of ON JN JO
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement.
To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.
The easiest way is to make a copy of the string each time, and modify the copy:
for(std::string::size_type i = 0 ; i < s.size() ; i++){
auto tmp=copy;
tmp.erase(i, 1);
std::cout << tmp << std::endl;
}
For correctness, the index variable should be a std::string::size_type
, what both length()
and size()
return (with size_t
and size()
naturally belonging together).
Your code almost got it right, except that it neglected to make the copy of the string each time, and s.at(i)++
didn't belong there.
You are not resetting tmp
to the original string value on each loop iteration, so it keeps erasing more and more characters from tmp
until it is empty.
You are also removing the wrong range of characters on each loop iteration.
You are also modifying the original string on each loop iteration to increment the value of its individual characters. Why are you doing that at all?
Try something more like this instead:
for(std::string::size_type i = 0 ; i < s.length() ; i++){
std::string tmp = s;
tmp.erase(i, 1);
std::cout << tmp << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With