| 1 | // LAF Base Library |
| 2 | // Copyright (c) 2001-2017 David Capello |
| 3 | // |
| 4 | // This file is released under the terms of the MIT license. |
| 5 | // Read LICENSE.txt for more information. |
| 6 | |
| 7 | #ifndef BASE_TRIM_STRING_H_INCLUDED |
| 8 | #define BASE_TRIM_STRING_H_INCLUDED |
| 9 | #pragma once |
| 10 | |
| 11 | #include <cctype> |
| 12 | #include <string> |
| 13 | |
| 14 | namespace base { |
| 15 | |
| 16 | template<typename Pred> |
| 17 | void trim_string(const std::string& input, |
| 18 | std::string& output, |
| 19 | const Pred& pred) |
| 20 | { |
| 21 | int i, j; |
| 22 | |
| 23 | for (i=0; i<(int)input.size(); ++i) |
| 24 | if (!pred(input.at(i))) |
| 25 | break; |
| 26 | |
| 27 | for (j=(int)input.size()-1; j>i; --j) |
| 28 | if (!pred(input.at(j))) |
| 29 | break; |
| 30 | |
| 31 | if (i < j) |
| 32 | output = input.substr(i, j - i + 1); |
| 33 | else |
| 34 | output = std::string(); |
| 35 | } |
| 36 | |
| 37 | inline void trim_string(const std::string& input, |
| 38 | std::string& output) { |
| 39 | trim_string<int(int)>(input, output, std::isspace); |
| 40 | } |
| 41 | |
| 42 | } |
| 43 | |
| 44 | #endif |
| 45 | |