Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading std::string, remove all special characters from a std::string

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_ifbut 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?

like image 980
johnkeere Avatar asked Jan 07 '14 12:01

johnkeere


People also ask

How do I remove special characters from a string in C++?

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.

Which code will remove all special characters?

You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.


1 Answers

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';
like image 185
111111 Avatar answered Oct 09 '22 15:10

111111