where can I find trim() in std C++?

Mar 22, 2023 at 5:25pm
I expected std::string to have a member function trim() but it does not. How to accomplish this??

Mar 22, 2023 at 5:32pm
In principle you could find the first and last non-whitespace character and take that substring.

But, if you do have boost library, then use the trim in it.
Mar 22, 2023 at 6:58pm
Trim, TrimBegin and TrimEnd are simple functions, the best approach is to implement them rather than introducing dependencies.

Sample:
https://stackoverflow.com/questions/216823/how-to-trim-an-stdstring
Mar 22, 2023 at 7:40pm
the problem with making these standard is twofold. First, expectations/requirements on them vary a little. Do you trim both front and back? Internal whitespace (eg 3 spaces to 1)? Do you kill all whitespace or only spaces?
you can very easily write these with find/replace or regex or std transform etc.
Mar 23, 2023 at 10:31am
Using ranges, then possibly something like this which will trim white-space from left and right of the given string and also return that trimmed value:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <ranges>
#include <string>
#include <iostream>
#include <cctype>

std::string& trim(std::string& in) {
	return in = std::ranges::to<std::string>(in |
		std::views::drop_while(std::isspace) | std::views::reverse |
		std::views::drop_while(std::isspace) | std::views::reverse);
}

int main() {
	std::string s { "   qwe   " };

	trim(s);

	std::cout << '!' << s << "!\n";
}


Which displays:


!qwe!

Last edited on Mar 23, 2023 at 11:01am
Topic archived. No new replies allowed.