Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 std::string을 자르는 가장 좋은 방법은 무엇입니까?

<시간/>

여기서는 C++에서 문자열을 자르는 방법을 살펴보겠습니다. 자르기 문자열은 문자열의 왼쪽과 오른쪽 부분에서 공백을 제거하는 것을 의미합니다.

C++ 문자열을 다듬기 위해 부스트 문자열 라이브러리를 사용합니다. 해당 라이브러리에는 trim_left() 및 trim_right()라는 두 가지 다른 메서드가 있습니다. 문자열을 완전히 자르려면 둘 다 사용할 수 있습니다.

예시

#include<iostream>
#include<boost/algorithm/string.hpp>
using namespace std;
main(){
   string myStr = " This is a string ";
   cout << "The string is: (" << myStr << ")" << endl;
   //trim the string
   boost::trim_right(myStr);
   cout << "The string is: (" << myStr << ")" << endl;
   boost::trim_left(myStr);
   cout << "The string is: (" << myStr << ")" << endl;
}

출력

$ g++ test.cpp
$ ./a.out
The string is: (       This is a string         )
The string is: (       This is a string)
The string is: (This is a string)
$