substr

2025. 1. 2. 17:58·알고리즘(코딩테스트)

수업을 듣던 도중 substr 함수를 접하게 되어서, 이번 기회에 잘 기억해 보고자 다시 정리를 해보았다.

아래의 자료를 참고해서 정리해 보았다.

https://en.cppreference.com/w/cpp/string/basic_string/substr

 

std::basic_string<CharT,Traits,Allocator>::substr - cppreference.com

(1) basic_string substr( size_type pos = 0, size_type count = npos ) const; (until C++23) (constexpr since C++20) constexpr basic_string     substr( size_type pos = 0, size_type count = npos ) const&; (since C++23) constexpr basic_string substr( size_typ

en.cppreference.com

https://modoocode.com/235

 

C++ 레퍼런스 - string 의 substr 함수

모두의 코드 C++ 레퍼런스 - string 의 substr 함수 작성일 : 2020-07-17 이 글은 159955 번 읽혔습니다. 문자열의 일부를 리턴한다. 문자열의 pos 번째 문자 부터 count 길이 만큼의 문자열을 리턴한다. 만약

modoocode.com

1. substr

basic_string substr(size_type pos = 0, size_type count = npos) const;
  • #include <string> 을 통해 사용할 수 있다.
  • pos는 첫번째 character의 위치이며, 해당 위치까지 포함된다.
  • count는 우리가 원하는 substring의 길이이다.
  • 원래 string의 [pos, pos+count) 인 값을 리턴해주는 함수이다.
  • 만일 string의 길이보다 더 긴 값을 넣는다면, out_of_range 예외를 발생시킨다.
  • 시간 복잡도는 count에 따라 선형적으로 증가한다. O(N)

2. 간단한 예시

  • sub1에서는 인자를 하나만 주는 경우이고, 이 경우 리턴값은 [pos, size())가 된다.
  • sub3에서는 pos + count가 바운더리를 넘어간 경우인데 이때에도 리턴값은 [pos, size())가 된다.
  • pos가 바운더리를 벗어난 경우는 out_of_range 예외가 발생한다. 
#include <string>
#include <iostream>
using namespace std;

int main()
{
    std::string a = "0123456789abcdefghij";

    //count가 없는 경우
    //[pos, size()) 반환
    std::string sub1 = a.substr(10); //abcdefghij
    std::cout << sub1 << '\n';

    //pos와 count둘 다 제대로 존재
    //[pos, pos + count) 반환
    std::string sub2 = a.substr(5, 3); //567
    std::cout << sub2 << '\n';

    //pos는 바운더리 안에있지만, 
    //count가 바운더리를 벗어난 경우
    //[pos, size()) 반환
    std::string sub3 = a.substr(a.size() - 3, 50); //hij
    std::cout << sub3 << '\n';

    //pos가 바운더리 벗어난 경우
    //out_of_range 
}

3. 간단한 문제 예시

input이 "abc" 인 경우 반환값으로 ["abc", "bca", "cab"] 가 나오도록 하는 함수 만들기

  • 이 문제를 보고 처음으로 생각했던 풀이
vector<string> solution(const string& str)
{
	vector<string> answer;

	for (int i = 0; i < str.size(); ++i)
	{
		string temp;
		for (int j = i; j < i + str.size(); ++j)
		{
			temp += str[j % str.size()];
		}
		answer.push_back(temp);
	}

	return answer;
}
  • substr을 사용한 풀이
vector<string> solution(const string& str)
{
	vector<string> answer;

	for (int i = 0; i < str.size(); ++i)
	{
		string first = str.substr(i);
		string other = str.substr(0, i);
		
		answer.push_back(first + other);
	}	

	return answer;
}

'알고리즘(코딩테스트)' 카테고리의 다른 글

unordered_map 순환  (1) 2025.02.04
허프만 코딩 & 유클리드 호제법  (0) 2025.01.07
string 관련 함수들 (tolower, isalpha, transform)  (3) 2025.01.03
1차원 BFS, DP  (0) 2025.01.02
2차원 vector 선언 및 sort  (1) 2024.12.27
'알고리즘(코딩테스트)' 카테고리의 다른 글
  • 허프만 코딩 & 유클리드 호제법
  • string 관련 함수들 (tolower, isalpha, transform)
  • 1차원 BFS, DP
  • 2차원 vector 선언 및 sort
gbleem
gbleem
gbleem 님의 블로그 입니다.
  • gbleem
    gbleem 님의 블로그
    gbleem
  • 전체
    오늘
    어제
    • 분류 전체보기 (184)
      • Unreal Engine (73)
      • C++ (19)
      • 알고리즘(코딩테스트) (27)
      • TIL (60)
      • CS (4)
      • 툴 (1)
  • 블로그 메뉴

    • 홈
    • 카테고리
  • 링크

    • 과제용 깃허브
    • 깃허브
    • velog
  • 공지사항

  • 인기 글

  • 태그

    매크로 지정자
    motion matching
    BFS
    템플릿
    actor 클래스
    C++
    addonscreendebugmessage
    map을 vector로 복사
    gamestate
    상속
    enhanced input system
    DP
    character animation
    additive animation
    blend pose
    Vector
    싱글턴
    const
    cin함수
    applydamage
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
gbleem
substr
상단으로

티스토리툴바