find_first_not_of()

김민수·2025년 2월 13일

C++

목록 보기
68/68

find_first_not_of(n) 함수는 문자열에서 n이 처음으로 아닌 문자가 등장하는 위치를 찾는 함수다.


size_t std::string::find_first_not_of(const std::string& chars, size_t pos = 0) const;
size_t std::string::find_first_not_of(char ch, size_t pos = 0) const;

인자

  • chars (문자열) → 찾고자 하는 제외할 문자들 (예: "0" → '0'이 아닌 첫 번째 문자를 찾음)
  • ch (문자) → 특정 문자 하나만 제외 (예: '0')
  • pos (기본값: 0) → 검색을 시작할 위치

반환값

  • 첫 번째로 chars에 없는 문자의 인덱스를 반환
  • 만약 모든 문자가 chars에 포함되어 있다면 string::npos 반환

#include <iostream>
#include <string>

using namespace std;

int main() {
    string binary = "00001010";  // 2진수 "1010" 앞에 불필요한 '0'이 존재

    // '0'이 아닌 문자가 등장하는 첫 번째 위치 찾기
    size_t firstOne = binary.find_first_not_of('0');

    // 앞의 '0' 제거
    binary.erase(0, firstOne);

    cout << "변환된 2진수: " << binary << endl;  // "1010" 출력

    return 0;
}
profile
안녕하세요

0개의 댓글