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 using at
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
and std::remove_if
but I need to eliminate all I mean special characters and spaces too. This means I need to include all the conditions that isspace()
/ 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?
Master C and Embedded C Programming- Learn as you go In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.
You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from 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';
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