C와 C++의 문자열
이 레슨에서는 C의 문자 배열과 C++의 std::string을 비교하며 길이 구하기, 이어 붙이기, 비교, 검색을 해 봅니다.
소개
C는 보이지 않는 문자 '\0'으로 끝나는 char 배열에 텍스트를 저장하며, 배열에 공간이 충분한지는 프로그래머가 책임져야 합니다. C++는 메모리를 스스로 관리하는 문자열 타입 std::string을 제공해 텍스트 작업을 훨씬 안전하고 편리하게 만들어 줍니다.
핵심 정리
- 컴파일러 경고(compiler warnings)를 켜고 모두 고치세요.
- 각 값의 타입과 수명(lifetime)을 정확히 이해하세요.
- 입력 데이터와 배열 인덱스의 범위를 항상 확인하세요.
C와 C++ 코드 예제
C
main.c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
/* A C string is a char array that ends with '\0'. */
char name[32] = "Ada";
printf("%s has %zu letters\n", name, strlen(name));
/* strcat appends; the array must have room for the result. */
strcat(name, " Lovelace");
printf("%s\n", name);
/* strcmp returns 0 when two strings are equal. */
printf("equal: %d\n", strcmp("cat", "cat") == 0);
/* Walk the characters until the terminating '\0'. */
char upper[32];
size_t i = 0;
for (; name[i] != '\0'; i++) {
upper[i] = (char)toupper((unsigned char)name[i]);
}
upper[i] = '\0';
printf("%s\n", upper);
/* strstr finds a substring and returns a pointer to it, or NULL. */
printf("contains \"love\": %s\n", strstr("lovelace", "love") ? "yes" : "no");
return 0;
}
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
C++
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
// std::string manages its own memory and grows as needed.
std::string name = "Ada";
std::cout << name << " has " << name.size() << " letters\n";
name += " Lovelace";
std::cout << name << '\n';
// == compares the contents of two strings.
std::cout << "equal: " << (std::string("cat") == "cat") << '\n';
std::string upper = name;
std::transform(upper.begin(), upper.end(), upper.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
std::cout << upper << '\n';
// find returns std::string::npos when the text is missing.
std::string word = "lovelace";
std::cout << "contains \"love\": " << (word.find("love") != std::string::npos ? "yes" : "no") << '\n';
std::cout << "first name: " << name.substr(0, 3) << '\n';
}
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
first name: Ada
C와 C++ 비교
C의 strlen, strcat, strcmp, strstr 함수는 문자 배열을 직접 다루며, 이어 붙일 때 배열이 충분히 크지 않으면 버퍼 오버플로(buffer overflow)가 생길 수 있습니다. std::string은 size(), +=, ==, find(), substr()을 제공하고 필요하면 메모리를 스스로 늘리기 때문에 이런 문제를 피할 수 있습니다.
C
C는 작은 절차형 함수를 쓰고, 데이터가 메모리에 어떻게 표현되는지 그대로 드러냅니다.
C++
C++는 여전히 저수준 작업을 할 수 있으면서, 라이브러리 타입과 더 안전한 추상화를 더합니다.
연습 문제
두 버전을 모두 실행한 다음 코드를 바꿔 보면서 각 언어가 주는 안전성의 차이를 살펴보세요.
- 잘못된 입력과 경계값으로 테스트해 보세요.
- -Wall -Wextra -Wpedantic 옵션으로 컴파일해 경고를 더 많이 켜 보세요.
- 공통 선언은 헤더 파일에, 구현은 별도의 파일에 두어 보세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Count Uppercase Letters Count the capital letters in a text. 쉬움
- Initials From a Name Build uppercase initials from a full name. 쉬움
- Replace Spaces With Dashes Turn spaces into dashes to make a URL-style slug. 쉬움