문자열(string)은 널 문자(null character, '\0')로 끝나는 1차원 문자 배열입니다. 문자열의 길이란 널 문자 앞에 위치한 문자들의 개수를 의미합니다.
예를 들어 다음과 같습니다.
char str[] = "The sky is blue"; 위 문자열의 문자 개수 = 15
문자열의 길이를 구하는 프로그램은 다음과 같습니다.
예제 1: while 루프 사용하기
#include<iostream>
using namespace std;
int main() {
char str[] = "Apple";
int count = 0;
while (str[count] != '\0')
count++;
cout<<"The string is "<<str<<endl;
cout <<"The length of the string is "<<count<<endl;
return 0;
}출력 결과
The string is Apple The length of the string is 5
위 프로그램에서는 while 루프 안에서 count 변수를 하나씩 증가시키며, 문자열에서 널 문자('\0')가 나타날 때까지 반복합니다. 루프가 종료되면 count 변수에는 곧 문자열의 길이가 저장됩니다. 해당 코드는 다음과 같습니다.
while (str[count] != '\0') count++;
문자열의 길이를 구한 후에는 화면에 출력하여 결과를 확인합니다. 이 과정은 아래 코드 조각으로 나타낼 수 있습니다.
cout<<"The string is "<<str<<endl; cout<<"The length of the string is "<<count<<endl;
예제 2: strlen() 함수 사용하기
직접 루프를 작성하지 않고도, <string.h>(C++에서는 <cstring>) 헤더에 포함된 strlen() 함수를 사용하면 더 간단하게 문자열의 길이를 구할 수 있습니다. 이 방법을 보여주는 프로그램은 다음과 같습니다.
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char str[] = "Grapes are green";
int count = 0;
cout<<"The string is "<<str<<endl;
cout <<"The length of the string is "<<strlen(str);
return 0;
}출력 결과
The string is Grapes are green The length of the string is 16
두 방법의 차이점
while 루프를 직접 작성하는 방식은 문자열 길이 계산의 내부 동작 원리를 이해하는 데 도움이 되어 학습 목적에 적합합니다. 반면 strlen() 함수는 표준 라이브러리에서 최적화된 구현을 제공하므로, 실무 코드에서는 간결성과 성능 면에서 더 유리합니다. 다만 strlen()은 널 문자로 올바르게 종료되지 않은 배열에 사용할 경우 정의되지 않은 동작(undefined behavior)이 발생할 수 있으므로 주의해야 합니다.