티스토리 뷰

공부한거/C++

#include <string>

tl;dr 2024. 11. 21. 22:37
#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, world!";  // 리터럴로 초기화
    std::string str2("C++ string");     // 생성자 사용
    std::string str3(str1);             // 복사 생성자
    std::string str4(5, '*');           // 반복 문자 ('*****')

    std::cout << str1 << std::endl;  // 출력: Hello, world!
    std::cout << str2 << std::endl; // 출력: C++ string
    std::cout << str4 << std::endl;  // 출력: *****

    return 0;
}

B. 문자열 연산

std::string은 다양한 연산을 지원합니다.

  • 문자열 연결
    #include <iostream>
    #include <string>
    
    int main() {
        std::string str1 = "Hello, ";
        std::string str2 = "world!";
        std::string result = str1 + str2; // 문자열 합치기
        std::cout << result << std::endl; // 출력: Hello, world!
    }

  • 문자열 비교
#include <iostream>
#include <string>

int main() {
    std::string str1 = "abc";
    std::string str2 = "def";
    if (str1 < str2) {
        std::cout << "str1 is less than str2" << std::endl;
    }
}
  • 부분 문자열 추출
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    std::string sub = str.substr(7, 5); // "world" 추출
    std::cout << sub << std::endl;
}
  • 문자 접근
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    char c = str[1];   // 'e'
    str[0] = 'h';      // "hello"로 변경
    std::cout<< str << endl;
}

C. 문자열 길이

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    std::cout << "Length: " << str.size() << std::endl;  // 출력: 5
}

D. 반복자 사용

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        std::cout << *it;
    }
    return 0;
}

3. 주요 메서드

문자열 관련 메서드

메서드설명예제 코드

size() / length() 문자열 길이 반환 str.size()
empty() 문자열이 비어 있는지 확인 if (str.empty()) { /* ... */ }
clear() 문자열 비우기 str.clear();
substr(pos, len) 특정 위치에서 부분 문자열 추출 str.substr(7, 5)
find(sub) 부분 문자열의 첫 번째 위치 반환, 실패 시 npos if (str.find("world") != std::string::npos)
replace(pos, len, s) 문자열 일부를 다른 문자열로 대체 str.replace(0, 5, "Hi")

입력 및 출력

메서드설명예제 코드

getline(cin, str) 입력된 전체 문자열 읽기 std::getline(std::cin, str)
push_back(c) 문자열 끝에 문자 추가 str.push_back('!');
pop_back() 문자열 끝 문자 제거 str.pop_back();

 

'공부한거 > C++' 카테고리의 다른 글

#include<utility>  (0) 2024.11.22
#include <exception>  (0) 2024.11.21
#include <array>  (0) 2024.11.21
느낌대로 namespace 정의  (0) 2024.11.21
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함