문제

C에서는 콘솔에서 입력을 읽을 수있는 작은 프로그램을 작성하고 있습니다. 그런 다음 숯 배열에 넣으십시오. 그 후 나는 배열을 단어로 나누어야합니다. 어떻게 해야할지 잘 모르겠습니다. 지금까지 나는 입력을 숯 어레이에 넣었습니다. 빈 캐릭터를 기반으로 토큰 화하는 방법이 있는지 알아야합니다. 또는이 문제를 처리하는 방법에 대한 다른 제안. 감사.

견본:

입력 : 이것은 단지 테스트입니다

배열 : [t, h, i, s, s, i, s ,, o, n, l, y, a, a, t, e, s, t, null

나는 문자열 배열을 얻고 싶습니다 [이것은, A, A, Test, NULL

main() {

    char msg[50], ch;
    int i = 0;

    printf("***Reading words in your input*****\n\n");
    printf("Type something terminated by ENTER button\n");

    while ((ch = getchar()) != '\n')
        msg[i++] = ch;

    msg[i] = '\0';

    i = 0;

    while (msg[i] != '\0')
        putchar(msg[i++]);
    printf("\n");

}
도움이 되었습니까?

해결책

예, 사용하십시오 strtok 기능:

char* token = strtok(msg, " ");
while (token != NULL) {
  printf("%s", token);
  token = strtok(NULL, " ");
}

다른 팁

파일이 끝날 때까지 모든 단어를 읽으려면 (Newline에서 멈추지 않음) 더 간단합니다.

#include <stdio.h>
int main(){
    char b[999];
    while (scanf("%s",b)==1)
        puts(b);
    return 0;
}

SCANF의 반환 값은 성공적으로 구문 분석 된 필드 수입니다. Whitespace는 "%S"필드를 분리하는 역할을하므로 원하는 토큰을 얻습니다. 물론 먼저 줄을 읽는 경우 SSCANF를 사용할 수 있습니다.

문자열 배열을 하나씩 처리하는 대신 문자열 배열을 축적하려면 (위의 "Puts (b)"를 하나씩 처리하려면 Reloc, Malloc, Strcpy 및 Strlen을 사용하여 손을 더러워야합니다. 고정 된 크기의 버퍼는 어쨌든 불쾌합니다.

C는 단어를 사용하는 의미에서 문자열이 없습니다. C에는 다양한 문자가 있습니다.

문자열 배열을 원한다면 ... 숯불 배열과 비슷한 것을 가질 수 있습니다.

그러나 각 배열에는 미리 결정된 크기가 있으며 더 많은 "문자열"을 추가하거나 사용 가능한 공간보다 길게 만들 수 없습니다. 다른 옵션 (char 배열 배열 대신)은 Malloc () 및 친구의 포인터와 메모리를 사용하는 것입니다 (Poonters, Malloc () 및 친구에 대한 토론을 다른 시간 동안 남겨 두는 것입니다).

char 배열 배열을 정의하고 공백으로 문장을 분할하려면이 작업을 수행 할 수 있습니다.

char array_of_string[10][6]; /* 10 strings of a maximum of 5 characters each, plus the NUL */
char msg[50] = "this is a test";
/* now split the msg and put the words in array_of_string */
int string_num = 0;
int word_size = 0;
int msg_index = 0;

while (msg[msg_index] != '\0') {
    if (msg[msg_index] != ' ') {
        /* add the character to the proper place in array_of_string */
        array_of_string[string_num][word_size] = msg[msg_index];
        /* and update word_size for next time through the loop */
        word_size++; /* needs check for reserved word size (5) */
    } else {
        /* a space! */
        /* first, terminate the current word */
        array_of_string[string_num][word_size] = '\0';
        /* prepare to start the next word */
        string_num++; /* needs check for reserved number of "strings" (10) */
        word_size = 0;
    }
}
/* array_of_string[0] is now "this"
 * array_of_string[1] is now "is"
 * ...
 */
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top