To clear all the opening characters of std:string

Asked 1 years ago, Updated 1 years ago, 86 views

I want to erase all the opening characters of the string (including \n, \r, \t). I'm using the method below. Is there a better way? Oh, and tell me how to erase the opening text in front of me

std::string s;
s.erase(s.find_last_not_of(" \n\r\t")+1);

c++ trim stdstring

2022-09-21 15:56

1 Answers

It depends, but I use 3 methods

#include <algorithm> 
#include <functional> 
#include <cctype>
#include <locale>

//Remove opening characters in front of you
static inline std::string &ltrim(std::string &s) {
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
        return s;
}

//Remove open characters after
static inline std::string &rtrim(std::string &s) {
        s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
        return s;
}

//Remove open characters at both ends
static inline std::string &trim(std::string &s) {
        return ltrim(rtrim(s));
}


2022-09-21 15:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.