Reading std::string, remove all special characters from a std::string
To get the first four characters:
std::string first4=str.substr(0, 4);
To remove anything that isspace and isalpha predicates (although I think I misunderstood, here, do you mean isspace and is not isalpha??):
str.erase(std::remove_if(str.begin(), str.end(),
[](char c) { return std::isspace(c) || std::isalpha(c); } ),
str.end());
You can append to the string using op+=
. For example:
str+="hello";
str+='c';
Admin
Updated on June 13, 2022Comments
-
Admin almost 2 years
I am very new to this forum and c++. So pardon me for my doubts/ questions. I am trying to read a
std::string
. I know I can access the elements usingat
or[int]
operator. I've 2 questions:1) remove or erase all special characters from string (includes spaces)
2) read only first 4 characters or letters from this string
For 1), I am checking on
std::erase
andstd::remove_if
but I need to eliminate all I mean special characters and spaces too. This means I need to include all the conditions thatisspace()
/isalpha()
and so on. Is there no single method to remove all at once?For 2), I can access the string like an array, I mean string[0], string[1], string[2], string[3]. But I can't add this into single string?
Please let me know how can I achieve this?