std
::
string
str =
" Hello, world! "
;
std
::
cout
<<
"Original string: "
<< str <<
std
::
endl
;
std
::
cout
<<
"Trimmed string: "
<< trim(str) <<
std
::
endl
;
return
0
;
使用 STL 中的 find_first_not_of() 和 find_last_not_of() 函数:
#include <iostream>
#include <string>
std::string trim(std::string str)
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos) return str;
size_t last = str.find_last_not_of(' ');
return str.substr(first, last - first + 1);
int main()
std::string str = " Hello, world! ";
std::cout << "Original string: " << str << std::endl;
std::cout << "Trimmed string: " << trim(str) << std::endl;
return 0;