본문 바로가기

[C++] std::string

  • std::string 생성
 // 문자열을 초기화하여 생성
 std::string str1 = "Hello, world!";

// 빈 문자열 생성
std::string str2;
std::string str22{};
std::string str222 = {};

// 문자 배열로부터 생성
char char_array[] = {'H', 'e', 'l', 'l', 'o'};
std::string str3(char_array);

// 특정 문자 반복하여 생성
std::string str4(5, 'X'); // "XXXXX"

.

  • std::string 문자열 길이 구하기
std::string str = "Hello, world!";
std::cout << "Length of the string: " << str.length() << std::endl;
std::cout << "Length of the string: " << str.size() << std::endl;

 

  • std::string  인덱스를 사용한 문자 접근
std::string str = "Hello";
char ch = str[1]; // ch에는 'e'가 할당됨 (인덱스는 0부터 시작)

 

  • std::string  문자열 조작
//문자열 추가
std::string str1 = "Hello";
str1.append(", world!");
std::cout << str1 << std::endl; // "Hello, world!"

//특정 위치에 문자열 삽입
std::string str2 = "Hello!";
str2.insert(5, " world");
std::cout << str2 << std::endl; // "Hello world!"

//특정 범위 문자열 삭제
std::string str3 = "Hello, world!";
str3.erase(7, 6); // 인덱스 7부터 6개의 문자를 삭제
std::cout << str3 << std::endl; // "Hello!"

 

  • std::string  문자열 찾기
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    char ch = 'o';

    // 문자열에서 첫 번째로 등장하는 문자 찾기
    size_t pos = str.find(ch); //pos = 4
    if (pos != std::string::npos) {
        std::cout << "Found '" << ch << "' at position: " << pos << std::endl;
    } else {
        std::cout << "Character '" << ch << "' not found" << std::endl;
    }

    return 0;
}

 

  • std::string  문자열 비교
std::string str1 = "apple";
std::string str2 = "banana";

//This comparison is based on dictionary order
int result = str1.compare(str2);
if (result == 0) {
    std::cout << "str1 and str2 are equal" << std::endl;
} else if (result < 0) {
    std::cout << "str1 is less than str2" << std::endl;
} else {
    std::cout << "str1 is greater than str2" << std::endl;
}

 

  • std::string  부분 문자열 복사
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";

    // 부분 문자열 복사 (인덱스 7부터 5개의 문자)
    std::string substring = str.substr(7, 5); // "world"

    // 복사된 부분 문자열 출력
    std::cout << "Original string: " << str << std::endl;
    std::cout << "Substring: " << substring << std::endl;

    return 0;
}

 

 

'C&C++' 카테고리의 다른 글

[C++11] cstdint  (0) 2024.07.29
[C++] 소수점 출력  (0) 2024.07.28
[C++11] thread  (0) 2024.06.29
[C++17] filesystem  (0) 2024.06.29
[C++11] constexpr  (0) 2024.06.23