Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete one character from a string at a time?

Tags:

c++

string

loops

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

like image 334
Gman Avatar asked Dec 06 '16 01:12

Gman


People also ask

How do I remove one character from a string?

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.

How do I remove a few character from a string?

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.

How do I remove a specific part of a string?

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.


2 Answers

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.

like image 118
Sam Varshavchik Avatar answered Sep 22 '22 14:09

Sam Varshavchik


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;
}
like image 29
Remy Lebeau Avatar answered Sep 25 '22 14:09

Remy Lebeau