The Essentials of C++, David hunter

Chapter 7. Working with Character Strings 문자열 다루기

7.1 Character Strings 문자열

  • Character strings in C++ are implemented as arrays of characters. Two methods for declaring and initializing a string are illustrated below.

  • C++에서 문자열은 문자 배열로 구현됩니다. 문자열을 선언하고 초기화하는 두 가지 방법은 아래와 같이 나와 있습니다.

char greeting[32] = "Hello World!";
char name[] = "Joan Smith";
  • The first example allocates 32 characters for greeting and loads “Hello World” starting at greeting[0]. Extra space is unused. The second example allocates to name exactly the amount of space required to store the string “Joan Smith”.

  • 첫 번째 예제에서는 32개의 문자를 greeting에 할당하고 “Hello World”를 greeting[0]에서 시작하여 로드합니다. 추가 공간은 사용되지 않습니다. 두 번째 예제에서는 “Joan Smith” 문자열을 저장하는 데 필요한 정확한 공간만 name에 할당됩니다.

  • C++ provides a library of string processing functions in the header file “string.h”. These are summarized in the tables below. Note that calls to the “destructive” string functions result in changes to the string specified as the first argument to the function. Consequently, these cannot be called with a const string as the first argument.

  • C++는 “string.h” 헤더 파일에 문자열 처리 함수 라이브러리를 제공합니다. 이러한 함수들은 아래 표에 요약되어 있습니다. 주의할 점은 “파괴적인” 문자열 함수를 호출하면 함수의 첫 번째 인수로 지정된 문자열이 변경됩니다. 따라서 첫 번째 인수로 const 문자열을 사용하여 이러한 함수를 호출할 수 없습니다.

Table 7.1
Destructive String Functions Table
Function Description
int strcmp(char* s1, char* s2) Returns 0 if s1 is equal to s2, -1 if s1 is less than s2, and +1 if s1 is greater than s2.
  s1과 s2가 같으면 0을 반환하고, s1이 s2보다 작으면 -1을 반환하고, s1이 s2보다 크면 +1을 반환합니다.
int strncmp(char* s1, char* s2) Compare at most n characters in s1 and s2
  s1과 s2의 최대 n개 문자를 비교합니다.
int strlen(char* s) String length
  문자열의 길이를 반환합니다.
char* strchr(char* s, char c) Returns pointer to first occurrence of c in s
  s에서 문자 c의 첫 번째 발생 지점을 가리키는 포인터를 반환합니다.
char* strrchr(char* s, char c) Returns pointer to last occurrence of c in s
  s에서 문자 c의 마지막 발생 지점을 가리키는 포인터를 반환합니다.
char* strpbrk(char* s1, char* s2) Returns pointer to first occurrence in s1 of any of the characters that are in s2
  s1에서 s2에 포함된 문자 중 첫 번째 발견된 문자를 가리키는 포인터를 반환합니다.
int strspn(char* s1, char *s2) Returns of the length of the largest prefix of s1 that consists entirely of characters in s2
  s1의 가장 긴 접두어가 s2의 문자로만 구성된 경우 그 길이를 반환합니다.
int strcspn(char* s1, char* s2) Return the length of the largest prefix of s1 that consists entirely of characters not in s2
  s1의 가장 긴 접두어가 s2의 문자로 구성되지 않은 경우 그 길이를 반환합니다.
Table 7.2
Nondestructive String Functions Table
function description
char* strcpy(char* s1, char* s2) copies s2 into s1
  s2를 s1으로 복사합니다.
char* strncpy(char* s1, char* s2, int n) copies at most n characters from s2 into s1
  s2에서 최대 n개의 문자를 s1으로 복사합니다.
char* strcat(char* s1, char* s2) Concatenates s2 on to the end of s1
  s2를 s1의 끝에 이어붙입니다.
char* strncat(char* s1, char* s2, int n) Concatenates at most n characters from s2 onto s1
  s2에서 최대 n개의 문자를 s1의 끝에 이어붙입니다.
char* strtok(char* s1, char* delim) Break s1 into tokens (See text)
  문자열 s1을 토큰으로 분리합니다. (자세한 내용은 텍스트 참조)
  • To string library package adopts the convention of using the character ‘\0’ to mark the end of a string. This “end of string” marker is automatically inserted and maintained by the library functions, and for most purposes the programmer need not be aware of its existence. However, it may be important to remember that every string will contain this one additional characters . Thus, the variable greeting can hold at most 31 characters of data.

  • 문자열 라이브러리 패키지는 문자열의 끝을 표시하기 위해 문자 ‘\0’을 사용하는 규칙을 채택합니다. 이 “문자열 끝” 마커는 라이브러리 함수에 의해 자동으로 삽입되고 유지되며, 대부분의 목적에 있어서 프로그래머는 그 존재를 인식할 필요가 없습니다. 그러나 모든 문자열에는 이 추가 문자 하나가 포함되어 있을 수 있음을 기억하는 것이 중요할 수 있습니다. 따라서 변수 greeting은 최대 31개의 문자 데이터를 포함할 수 있습니다.

  • When comparing strings, characters from the two strings are compared in succession until the characters are not equal or until an end of string (‘\0’) is encountered. Similarly, when copying one string to another, successive characters are copied until the end of string mark in the source string is encountered. Because range checking is usually not the default, caution must be exercised when copying and comparing strings.

  • 문자열을 비교할 때는 두 문자열의 문자가 서로 다를 때까지 또는 문자열의 끝인 (‘\0’)을 만날 때까지 문자들을 차례대로 비교합니다. 마찬가지로, 한 문자열을 다른 문자열로 복사할 때도 원본 문자열의 끝에 있는 문자열 표시를 만날 때까지 문자들이 차례대로 복사됩니다. 일반적으로 범위 검사가 기본적으로 활성화되어 있지 않으므로 문자열을 복사하고 비교할 때 주의가 필요합니다.

  • The strtok function is used to process the individual “tokens” in a string. A token is a sequence of characters forming a meaningful lexical unit (a ward, for example). To use strtok, it should be called once with the first argument being the string to be processed and the second a string indicating the delimeter characters that mark the end of a token. After this call, the function will replace the first occurrence in s of a delim character with ‘\0’ and return a pointer to the first token in s. The first time the function is called this will usually be a pointer equal to s since a string usually begins with a token.

  • strtok 함수는 문자열 내의 개별 “토큰”을 처리하는 데 사용됩니다. 토큰은 의미 있는 어휘 단위 (예: 단어)를 형성하는 문자 시퀀스입니다. strtok을 사용하려면 첫 번째 인수로 처리할 문자열을 지정하고 두 번째 인수로 토큰의 끝을 나타내는 구분자 문자열을 지정해야 합니다. 이 호출 이후에 함수는 s의 첫 번째 나타난 delim 문자를 ‘\0’로 대체하고 s에서 첫 번째 토큰을 가리키는 포인터를 반환합니다. 함수가 처음 호출될 때, 일반적으로 이 포인터는 s와 같은 값일 것입니다. 왜냐하면 문자열은 일반적으로 토큰으로 시작하기 때문입니다.

  • Subsequent calls to strtok should be made using NULL as its first argument. The function will return a pointer to the next token in s each time it is called. It will return NULL when there are no more tokens in s. The program on the next page illustrates the use of strtok.

  • strtok 함수를 연속해서 호출할 때는 첫 번째 인수로 NULL을 사용해야 합니다. 이 함수는 호출될 때마다 s에서 다음 토큰을 가리키는 포인터를 반환합니다. s에 더 이상 토큰이 없을 때 NULL을 반환합니다. 다음 페이지의 프로그램은 strtok의 사용 예를 보여줍니다.

  • Also on the next page are a few examples illustrating the workings of some of the other string functions. All functions that return pointers return NULL if they are unsuccessful.

  • 다음 페이지에는 다른 몇 가지 문자열 함수의 작동 방식을 보여주는 몇 가지 예제도 있습니다. 포인터를 반환하는 모든 함수는 실패할 경우 NULL을 반환합니다.

Program illustrating use of the strtok function
#include <cstring>
#include <iostream>
using namespace std;

int main()
{
    // char *s = "This is it", *delim = " ", *tok; // 원본
    char s[] = "This is it";  // 문자열을 수정 가능한 배열로 복사
    const char *delim = " ";
    char *tok;

    // set up strtok for processing s and return pointer to first token
    tok = strtok(s, delim);

    do {
        cout << tok << '\n';
        // get pointer to the next token, nullptr if none
        tok = strtok(nullptr, delim);
    } while (tok != nullptr);
    return 0;
}