문자열 다루기
2025. 3. 27. 23:04ㆍProgramming Languages/C++
2.4 문자열 다루기
2.4.1 C 스타일 문자열
C 스타일 문자열은 널 종료 문자(\0)로 끝나는 문자 배열입니다:
#include <iostream>
#include <cstring> // C 스타일 문자열 함수
int main() {
// 문자열 선언 및 초기화
char greeting[20] = "Hello"; // 크기가 20인 문자 배열
char name[] = "홍길동"; // 크기가 자동으로 결정됨 (7바이트 + 널 문자)
// 문자열 길이 구하기
int length = strlen(greeting); // 5
std::cout << "길이: " << length << std::endl;
// 문자열 복사
char destination[20];
strcpy(destination, greeting); // greeting을 destination에 복사
// 문자열 연결
strcat(destination, ", World!"); // destination에 ", World!" 추가
std::cout << destination << std::endl; // "Hello, World!"
// 문자열 비교
if (strcmp(greeting, "Hello") == 0) {
std::cout << "문자열이 같습니다." << std::endl;
}
// 문자열 검색
char* position = strstr(destination, "World");
if (position != nullptr) {
std::cout << "World는 " << (position - destination) << "번째 위치에 있습니다." << std::endl;
}
return 0;
}
C 스타일 문자열의 단점:
- 버퍼 오버플로우 위험
- 메모리 관리의 어려움
- 문자열 조작의 불편함
2.4.2 std::string 클래스
C++의 std::string 클래스는 C 스타일 문자열의 단점을 보완하여 안전하고 편리한 문자열 처리를 제공합니다:
#include <iostream>
#include <string>
int main() {
// 문자열 선언 및 초기화
std::string greeting = "Hello";
std::string empty; // 빈 문자열
// 문자열 길이
int length = greeting.length(); // 또는 greeting.size()
std::cout << "길이: " << length << std::endl;
// 문자열 연결
greeting += ", World!"; // 연산자 오버로딩
std::cout << greeting << std::endl; // "Hello, World!"
// 문자열 추가 방법
greeting.append(" How are you?");
std::cout << greeting << std::endl; // "Hello, World! How are you?"
// 부분 문자열 추출
std::string sub = greeting.substr(0, 5); // "Hello" 추출
std::cout << "부분 문자열: " << sub << std::endl;
// 문자열 검색
size_t position = greeting.find("World");
if (position != std::string::npos) { // npos는 "not found"를 의미
std::cout << "World는 " << position << "번째 위치에 있습니다." << std::endl;
}
// 문자열 교체
greeting.replace(7, 5, "C++"); // 7번째 위치부터 5개 문자를 "C++"로 교체
std::cout << greeting << std::endl; // "Hello, C++! How are you?"
// 문자열 삽입
greeting.insert(13, " 언어");
std::cout << greeting << std::endl;
// 문자열 삭제
greeting.erase(7, 3); // 7번째 위치부터 3개 문자 삭제
std::cout << greeting << std::endl;
// 문자열 비교
if (greeting == "Hello") {
std::cout << "문자열이 같습니다." << std::endl;
} else {
std::cout << "문자열이 다릅니다." << std::endl;
}
// 개별 문자 접근
char firstChar = greeting[0]; // 'H'
std::cout << "첫 번째 문자: " << firstChar << std::endl;
// 문자열 반복 (C++11)
for (char c : greeting) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
2.4.3 문자열 변환
#include <iostream>
#include <string>
#include <sstream> // 문자열 스트림
int main() {
// 숫자를 문자열로 변환
int num = 123;
std::string numStr = std::to_string(num);
std::cout << "숫자 -> 문자열: " << numStr << std::endl;
// 문자열을 숫자로 변환 (C++11)
std::string pi = "3.14159";
double piValue = std::stod(pi); // string to double
int intValue = std::stoi("42"); // string to int
// 문자열 스트림 사용
std::stringstream ss;
ss << "나이: " << 25 << ", 키: " << 175.5;
std::string result = ss.str();
std::cout << result << std::endl;
// 문자열 스트림으로 파싱
std::stringstream parser("123 3.14 Hello");
int a;
double b;
std::string c;
parser >> a >> b >> c;
std::cout << "파싱 결과: " << a << ", " << b << ", " << c << std::endl;
return 0;
}
'Programming Languages > C++' 카테고리의 다른 글
챕터2. 실습 문제 (0) | 2025.03.27 |
---|---|
타입 별칭 및 auto 키워드 (0) | 2025.03.27 |
입출력 (0) | 2025.03.27 |
연산자 (0) | 2025.03.27 |
변수와 자료형 (0) | 2025.03.27 |