c++ combine erase and remove string [duplicate] - c++

This question already has answers here:
Difference between erase and remove
(7 answers)
Closed 8 years ago.
I saw someone use this line to remove white spaces from string stored in a vector, but I fail to understand the reason for using erase and remove this way?
The second question: how can I, instead of only removing white spaces, remove anything that is not a 'num' or a '-' ?
this is not the full code, it is only a snippet, will not compile. the vector simply contains raw strings of a text file, the strings were comma delimited, currently the strings could contain any possible char except the comma.
vector <string> vecS;
ifstream vecStream;
while(vecStream.good()) {
vecS.resize(i+1);
getline(vecStream, vecS.at(i), ',');
vector <string> vecS;
vecS.at(i).erase(remove( vecS.at(i).begin(), vecS.at(i).end(), ' '), vecS.at(i).end());
i++
}
EDIT; added more code, hope this is clearer now

but I fail to understand the reason for using erase and remove this
way?
std::remove basically rearranges the sequence so that the elements which are not to be removed are all shifted to the beginning of the sequence - a past-the-end iterator for that part, and effectively the new end of the sequence, is then returned.
There is absolutely no need for a file stream in that snippet though:
vector <string> vecS;
// Do something with vecS
for( auto& s : vecS )
s.erase( remove_if( std::begin(s), std::end(s),
[](char c){ return std::isspace(c); }), // Use isspace instead, that recognizes all white spaces
std::end(s) );

Related

How to search and delete characters in string

I'm trying to convert .fsp files to strings but new .fsp file is very abnormal. It contains some undesirable characters that I want to delete from string. How can I make it?
I have tried to search char in string and delete them but I dont know how to make it.
The string looks like this:
string s;
s = 144˙037˙412˙864;
and I need to make it just like that
s = 144037412864;
So I except result like this:
string s = 144037412864;
Thank you for help.
We can use the remove-erase idiom to remove unnecessary characters from the string! There's a function in <algorithm> called remove_if. What remove_if does is it removes elements that match some predicate. remove_if returns a iterator pointing to the new end of the container after all elements have been removed. I'll show you how to write a function that does the job!
#include <algorithm>
#include <string>
void erase_ticks(std::string& s) {
// Returns true for characters that should be removed
auto condition = [](char c) { return c == '`'; };
// Removes characters that match the condition,
// and returns the new endpoint of the string
auto new_end = std::remove_if(s.begin(), s.end(), condition);
// Erases characters from the new endpoint to the current endpoint
s.erase(new_end, s.end());
}
We can use this in main, and it works just as expected!
#include <iostream>
int main() {
std::string s("123`456`789");
std::cout << s << '\n'; // prints 123`456`789
erase_ticks(s);
std::cout << s << '\n'; // prints 123456789
}
This problem has two parts, first we need to identify any characters in the string which we don't want. From your use case it seems that anything that is not numeric needs to go. This is simple enough as the standard library defines a function std::isdigit (simply add the following inclusion "#include <locale>") which takes a character and returns a bool which indicates whether or not the character is numeric.
Second we need a way to quickly and cleanly remove all occurrences of these from the string. Thus we can use the 'Erase Remove' idiom to iterate through the string and do what we want.
string s = "123'4'5";
s.erase(std::remove_if(s.begin(), s.end(), [](char x)->bool {return !std::isdigit(x);}), s.end());
In the snippit above we're calling erase on the string which takes two iterators, the first refers to where we want to begin to delete from and the second tells the call where we want to delete to. The magic in this trick is actually all in the call to remove_if (include "#include <algorithm>" for it). remove_if actually works by shifting the elements (or characters) of string forward to the end of the string.
So "123'4'5'" becomes "12345'''", then it returns an iterator to where it shifted these characters to which is then passed to erase to tell it remove the characters starting here. In the end we're left with "12345" as expected.
Edit: Forgot to mention, remove_if also takes a predicate here I'm using a lambda which takes a character and returns a bool.

Copy a std::string using copy_if (into another string)

I'm wondering what's the best way to selectively copy_if characters from one string to another. I have something like
string buffer1("SomeUnknownwSizeAtCompileTime");
string buffer2; // WillBeAtMostSameSizeAsBuffer1ButMaybeLessAfterWeRemoveSpaces
buffer2.resize(buffer1.length());
std::copy_if(buffer1.begin(), buffer1.end(), buffer2.begin(), [](char c){
//don't copy spaces
return c != ' ';
});
buffer2 could potentially be a lot smaller than buffer1, yet we have to allocate the same amount of memory as buffer1's length. After copying however, buffer2's end iterator will point past the null termination character. I googled around and apparently this is by design, so now I'm wondering should I not be using copy_if with strings?
Thanks
You need to use std::back_inserter.
#include <iterator>
std::copy_if(buffer1.begin(), buffer1.end(), back_inserter(buffer2), [](char c){
//don't copy spaces
return c != ' ';
});
back_inserter(buffer2) returns a specialized iterator which appends to instead of overwriting the elements of buffer2.
For this to work correctly, you'll have to make sure that you start out with an empty buffer2. i.e. don't use:
buffer2.resize(buffer1.length());

std::string::erase doesn't work as I expected

There are many questions here on splitting string by comma. I am trying to make another one.
#include<iostream>
#include<algorithm>
#include<string>
#include<cctype>
int main()
{
std::string str1 = "1.11, 2.11, 3.11, 4.11, 5.11, ";
str1.erase(std::remove_if(str1.begin(), str1.end(), [](unsigned char x){return std::isspace(x);}));
std::cout<<"New string = "<<str1<<std::endl;
return 0;
}
But I am getting the unexpected output below.
New string = 1.11,2.11,3.11,4.11,5.11, 4.11, 5.11,
Did I miss something?
std::remove_if moves the non-removed elements to the front of the string, and returns iterator to the first element to be erased. You use the single iterator argument erase, which only erases a single element. To erase all of the matching characters, you need to use the two argument version, by passing end iterator:
str1.erase(
std::remove_if(
str1.begin(),
str1.end(),
[](unsigned char x){return std::isspace(x);}
),
str1.end() // this was missing
);
In case you were wondering why there are some non-space characters at the end, std::remove_if is not required the keep the eliminated elements intact, and some of them have been overwritten.
There are two iterator based versions of string::erase. One that erases a single character, and one that erases a range. You have to add the end of the range to get rid of all of it.
str1.erase(std::remove_if(str1.begin(), str1.end(),
[](unsigned char x){return std::isspace(x);}),
str1.end());
Your call to erase uses the single iterator argument overload, which removes 1 character. Add str1.end() as second argument to get the usual remove+erase idiom.

Removing Characters from String until it becomes empty

I can't get my head around this. I'm trying to remove all occurrences of a certain character within a string until the string becomes empty. I know we can remove all character occurrences from an std::string by using the combination of string::erase and std::remove like so:
s.erase(remove(s.begin(), s.end(), '.'), s.end());
where the '.' is the actual character to be removed. It even works if I try to remove certain characters. Now let's consider the following string: 'abababababababa'. What I'm trying to achieve is to reduce this string to ashes be removing all 'a's for startes, which will leave me with a couple of 'b's. Then remove all those 'b's which will leave me with an empty string. Of course this is just a part of my task but I could narrow it down for this problem. Here's my naive approach based on the upper combination of functions:
string s = "abababababababa";
while (!s.empty()) {
...
s.erase(remove(s.begin(), s.end(), s[0]), s.end());
...
}
Of course it doesn't work, I just can't seem to find out why. By debugging the application I can see how the "s" string is being modified. While the s.erase... works perfectly if I set a character constant for remove's third parameter it fails if I try to use char variables. Here's what the s string looks like after each iteration:
Removing[a] from [abababababababa] Result: baaaaaaa
Removing[b] from [baaaaaaa] Result: a
Removing[a] from [a] Result: -
While I expected 2 operations until a string should become empty - which works, if I hardcode the letters by hand and use s.erase twice - it actually takes 3 iteration. The most frustrating part however is the fact that, while I'm removing 'a' in the first iteration only the first 'a' is removed and all other 'b'.
Why is this happening? Is it the cause of how erase / remove works internally?
You have undefined behavior.
You get the results you get because std::remove takes the value to remove by reference, once s[0] has been removed, what happens to the reference to it then?
The simple solution is to create a temporary variable, assign e.g. s[0] to it, and pass the variable instead.
The behavior of function remove() template is equivalent to:
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator result = first;
while (first!=last) {
if (!(*first == val)) {
*result = move(*first);
++result;
}
++first;
}
return result;
}
As you see, the function will move the element different with val to the front of the range.
so in your case "ababababab",
if you call remove() like you did, the original s[0] is 'a', but it will be instead by 'b' during the remove(), the remaining code will remove the 'b', so the result is not right.
Like Joachim say, assign s[0] to a temporary variable.
the code is reference from http://www.cplusplus.com/reference/algorithm/remove/?kw=remove

Vector push_back on duplicate strings with the help of delimiter

I am trying to read the PATH Environment variable and remove any duplicates that are present in it using vector functionalities such as - sort, erase and unique. But as I've seen vector will delimit each element default by newline. When I get the path as C:\Program Files(x86)\..., its breaking at C:/ Program. This is my code so far:
char *path = getenv("PATH");
char str[10012] = "";
strcpy(str,path);
string strr(str);
vector<string> vec;
stringstream ss(strr);
string s;
while(ss >> s)
{
push_back(s);
}
sort(vec.begin(),vec.end());
vec.erase(unique(vec.begin(),vec.end()),vec.end());
for(unsigned i=0;i<vec.size();i++)
{
cout<<vec[i]<<endl;
}
Is it the delimiter problem? I need to pus_back at every ; and search for duplicates. Can anyone help me in this regard.
I would use a stringstream to chop it up, and the use a set to ensure there are no duplicates.
std::string p { std::getenv("PATH") }
std::set<string> set;
std::stringstream ss { p };
std::string s;
while(std::getline(ss, s, ':')) //this might need to be ';' for windows
{
set.insert(s);
}
for(const auto& elem : set)
std::cout << elem << std::endl;
Should you need to use a vector for some reason, you'd want to sort it with std::sort then remove duplicates with std::unique then erase the slack with erase.
std::sort(begin(vec), end(vec));
auto it=std::unique(begin(vec), end(vec));
vec.erase(it, end(vec));
EDIT: link to docs
http://en.cppreference.com/w/cpp/container/set
http://en.cppreference.com/w/cpp/algorithm/unique
http://en.cppreference.com/w/cpp/algorithm/sort
For this task it is better to use std::set<std::string> which will eliminate duplicates automatically. To read in PATH, use strtok to split it into substrings.
You need to use a different delimiter (':' or ';' to split the directories from the PATH, depending on the system). For instance, you can have a look at the std::getline() function to replace your current while () / push_back loop. This function allows you to specify a custom delimiter and would be a drop-in replacement in your code.
It isn't so much that std::vector<T> is delimiting anything but that the formatted input operator (operator>>()) for strings uses whitespace as delimiters. Other already posted about using std::getline() and the like. There are two other approaches:
Change what is considered to be whitespace for the stream! The std::string input operator uses the stream's std::locale object to obtain a std::ctype<char> facet which can be replaced. The std::ctype<char> facet has functions to do character classification and it can be used to consider, e.g., the character ';' as a space. It is a bit involved but a more solid approach than the next one.
I don't think path components can include newlines, i.e., a simple approach could be to replace all semicolons by newlines before reading the components:
std::string path(std::getenv("PATH"));
std::replace(path.begin(), path.end(), path.begin(), ';', '\n');
std::istringstream pin(path);
std::istream_iterator<std::string> pbegin(pin), pend;
std::vector<std::string> vec(pbegin, pend);
This approach may have the problem that the PATH may contain components which contain spaces: these would be split into individual object. You might want to replace spaces with another character (e.g., the now unused ';') and restore those at an appropriate to become spaces.