C++ does not provide any readily available API to trim a string value. Hence we need to use string methods find_first_not_of and find_last_not_of.
Trim starting and ending spaces (white space, tab, new line)
find_first_not_of - returns index of character which is among the set of the characters passed. Algorithm starts looking for it from beginning of the string.
find_last_not_of - returns index of character which is among the set of the characters passed. Algorithm starts looking for it from end of the string.
Following code trims leading chars first and then trailing chars. So execute both statements if complete trim needed.
Note: Do not include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string str = " Hello World! ";
str.erase(0, str.find_first_not_of(" \n\r\t")); // TRIM leading spaces
std::cout << "After left trim ::" << str << "::" << std::endl ;
str.erase(str.find_last_not_of(" \n\r\t") + 1); // TRIM ending spaces
std::cout << "After right trim ::" << str << "::" << std::endl;
return 0;
}
/********** OUTPUT **********
After left trim ::Hello World! ::
After right trim ::Hello World!::
*/
Trim characters instead of space at beginning, end of the string
find_first_not_of - returns index of character which is among the set of the characters passed. Algorithm starts looking for it from beginning of the string.
find_last_not_of - returns index of character which is among the set of the characters passed. Algorithm starts looking for it from end of the string.
Following code trims leading chars first and then trailing chars. So execute both statements if complete trim needed.
Note: Do not include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string str = " Hello World! ";
str.erase(0, str.find_first_not_of(" \n\r\t")); // TRIM leading spaces
std::cout << "After left trim ::" << str << "::" << std::endl ;
str.erase(str.find_last_not_of(" \n\r\t") + 1); // TRIM ending spaces
std::cout << "After right trim ::" << str << "::" << std::endl;
return 0;
}
/********** OUTPUT **********
After left trim ::Hello World! ::
After right trim ::Hello World!::
*/
Trim characters instead of space at beginning, end of the string
Sometimes it is required to remove few leading, trailing chars.
Ex: String content might be padded with stars (*) or it can have delimiters like =,| etc.
Following is the code to trim characters from a string.
#include <iostream>
#include <string>
void trim_chars(std::string& str, const char* chars)
{
str.erase(0, str.find_first_not_of(chars));
str.erase(str.find_last_not_of(chars));
}
int main()
{
std::string str = "xzHello World!zy";
trim_chars(str, "xyz");
std::cout << "After trim ::" << str << "::" << std::endl ;
return 0;
}
/********** OUTPUT **********
After trim ::Hello World::
*/
No comments:
Post a Comment