Language/C++

[C++] string::substr

hyowonii 2022. 2. 24. 22:23

주어진 문자열에서 부분문자열 추출하기

string substr (size_t pos = 0, size_t len = npos) const;

pos 위치부터 len개의 캐릭터를 문자열로 반환한다.

 

ex)

// string::substr
#include <iostream>
#include <string>
 
int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)
 
  std::string str2 = str.substr (3,5);     // "think"
 
  std::size_t pos = str.find("live");      // position of "live" in str
 
  std::string str3 = str.substr (pos);     // get from "live" to the end
 
  std::cout << str2 << ' ' << str3 << '\n';
 
  return 0;
}

[출력 결과]

think live in details.

 


[참고]

https://www.cplusplus.com/reference/string/string/substr/