0
点赞
收藏
分享

微信扫一扫

c++ 去除字符串首尾的空白字符


c++ 去除字符串首尾的空白字符

  • ​​方法一使用find_first_not_of和find_last_not_of​​
  • ​​方法二使用正则表达式(c++11)​​
  • ​​测试​​
  • ​​测试结果​​

方法一使用find_first_not_of和find_last_not_of

/**
* @brief Trimmed 去掉首尾 空格白
* @param str
*/
void Trimmed(std::string& str) {
str.erase(0, str.find_first_not_of(" \r\n\t\v\f"));
str.erase(str.find_last_not_of(" \r\n\t\v\f") + 1);
// std::cout << "Trimmed [" << str << "]" << std::endl;
}

方法二使用正则表达式(c++11)

/**
* @brief Trimmed_Regex 正则表达式 去字符串首尾的 空白 c++ 11
* @param str
*/
void Trimmed_Regex(std::string& str) {
std::regex e("([\\S].*[\\S])");
str = std::regex_replace (str,e,"$1",std::regex_constants::format_no_copy);
// std::cout << "Trimmed_Regex [" << str << "]" << std::endl;
//std::cout << "Trimmed_Regex [" << std::regex_replace (str,e,"$2") << "]" << std::endl;
}

测试

int main() {
//std::string str ("there is a subsequence in the string\n");
// std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub"

// // using string/c-string (3) version:
// std::cout << std::regex_replace (s,e,"sub-$2");

// // using range/c-string (6) version:

// std::cout << result;

// // with flags:
// std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
// std::cout << std::endl;

clock_t start;

std::string str = "\r\n \t\v\f { Test 123 78927849……&*%&*&*(【】)代收款 } \t\v\f \r\n";

std::cout << "[" << str << "]" << std::endl;

start = clock();
Trimmed_Regex(str);
std::cout << clock() - start << " Trimmed_Regex [" << str << "]" << std::endl;

start = clock();
Trimmed(str);
std::cout << clock() - start << " Trimmed [" << str << "]" << std::endl;
// std::string result;
// std::regex_replace (std::back_inserter(result), str.begin(), str.end(), e, "");
// std::cout << "[" << result << "]" << std::endl;
return 0;
}

测试结果

c++ 去除字符串首尾的空白字符_regex


举报

相关推荐

0 条评论