본문 바로가기

SW 지식/C 와 C++ 공부

[C++] String의 substr

substr : substring 을 줄인말인 것처럼 하위 문자열을 생성하여 리턴!

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

문자열의 'pos'번째 문자부터 'len' 길이 만큼의 하위 문자열을 반환합니다.

 

예를 들어, 아래와 같이 str이라는 변수의 string이 주어졌을 때,

substr()로 3번째 문자부터 길이 5만큼의 하위 문자열을 반환하고자 할 때 사용됩니다.

#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities.";

  std::string str2 = str.substr (3,5);     // "think"

  std::cout << str2 << '\n';

  return 0;
}

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

 

string::substr - C++ Reference

12345678910111213141516171819 // string::substr #include #include 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

www.cplusplus.com

 

추가로, 현재 보고 있는 코드에서는 아래와 같이 사용되는데요.

#define AtspiPath "/org/a11y/atspi/accessible"

std::string BridgeBase::StripPrefix(const std::string& path)
{
  auto size = strlen(AtspiPath);
  return path.substr(size + 1);
}

AtspiPath로 정의된 prefix를, 주어진 parameter인 path에서 제외하고 리턴하도록 하는 것입니다.

즉, 예를 들어, "/org/a11y/atspi/accessible/usr/opt/bin/" 과 같이 path가 들어오면, "/usr/opt/bin/" 이라는 하위 문자열을 반환할 것입니다.

'SW 지식 > C 와 C++ 공부' 카테고리의 다른 글

[C++] emplace 함수  (0) 2021.09.23
[C++] unordered_map 컨테이너  (0) 2021.09.23
[C++] std::function 은 무엇일까  (0) 2021.09.16
[C++] 람다 식 Lambda expressions  (0) 2021.09.16
[C++] mutable 변수  (0) 2021.09.03