[C++] 문자열 (C-style + std::string)

kimyb·2022년 12월 26일

문자열은 정말 중요하면서, c스타일과 헷갈리기에 여러 방법들을 한눈에 알아보자.
문자열을 사용하는 방법은 여러 가지가 있다.

1. C 스타일 문자열 (C-style Strings):

기본적으로 C를 배울때 알게되는 C-style 문자열은 종료 문자('\0')로 끝나는 문자의 배열. C++에서 C 스타일의 문자열을 사용할 수 있다.

	char a[] = "hello world1";						// stack 영역에 있는 char형 배열
	cout << "a size : " << sizeof(a) << endl;		// 13("hello world1" + "\0")
	cout << "a len : " << strlen(a) << endl;		// 12
	cout << "a  : " << a << endl;					// hello world1
	cout << endl;

	const char * b = "hello world2";				// stack에 b가 존재하고, b는 read-only 영역에 있는 "hello world2\0"를 가리킴.
	cout << "b size : "  << sizeof(b) << endl;		// 8 (pointer의 size)
	cout << "*b size : " << sizeof(*b) << endl;		// 1 (1개의 사이즈)
	cout << "b len : " << strlen(b) << endl;		// 12
	cout << "b : " << b << endl;					// hello world2
	cout << endl;



2. C++ 문자열 (C++ Strings):

C++에서 std::string 클래스를 사용하여 문자열을 다룰 수 있다. Strings은 표준 라이브러리 중 일부이며 문자열을 편리하게 처리할 수 있는 여러 멤버 함수를 가지고 있다.다.

#include <iostream>
#include <string>

int main() {
	// std::string은 class template으로, heap 메모리를 사용함.
	string c = "hello world";
	cout << c.find('o') << endl;					// 4  (찾는 문자열이 없는 경우에는 string::npos를 반환한다.)
	cout << "c size : " << sizeof(c) << endl;		// 컴파일러마다 다르지만, vs에서는 40
	cout << "c len : " << c.size() << endl;			// 11

	// 컴파일러마다 다르지만, optimization으로 문자열 크기가 작다면 heap에 넣지 안고 stack에 올리기도 함.
    return 0;
}

std::string은 동적으로 크기를 조절할 수 있으며, 문자열 추가, 삭제, 검색 등 다양한 문자열 조작이 가능하다.

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "C++ String!";
    std::string result = str1 + str2; // 문자열 연결
    std::cout << "Length: " << result.length() << std::endl; // 문자열 길이
    std::cout << "Substring: " << result.substr(7, 6) << std::endl; // 부분 문자열
    return 0;
}
profile
공부했던것을 정리.

0개의 댓글