source

공백마다 C 문자열 분할

goodcode 2022. 8. 13. 12:11
반응형

공백마다 C 문자열 분할

(입력으로서 취득한) 문장 전체를 다른 행으로 표시하는 프로그램을 C로 작성하고 싶다.지금까지 제가 한 일은 다음과 같습니다.


void manipulate(char *buffer);
int get_words(char *buffer);

int main(){
    char buff[100];

    printf("sizeof %d\nstrlen %d\n", sizeof(buff), strlen(buff));   // Debugging reasons

    bzero(buff, sizeof(buff));

    printf("Give me the text:\n");
    fgets(buff, sizeof(buff), stdin);

    manipulate(buff);
    return 0;
}

int get_words(char *buffer){                                        // Function that gets the word count, by counting the spaces.
    int count;
    int wordcount = 0;
    char ch;

    for (count = 0; count < strlen(buffer); count ++){
        ch = buffer[count];
        if((isblank(ch)) || (buffer[count] == '\0')){                   // if the character is blank, or null byte add 1 to the wordcounter
            wordcount += 1;
        }
    }
    printf("%d\n\n", wordcount);
    return wordcount;
}

void manipulate(char *buffer){
    int words = get_words(buffer);
    char *newbuff[words];
    char *ptr;
    int count = 0;
    int count2 = 0;
    char ch = '\n';

    ptr = buffer;
    bzero(newbuff, sizeof(newbuff));

    for (count = 0; count < 100; count ++){
        ch = buffer[count];
        if (isblank(ch) || buffer[count] == '\0'){
            buffer[count] = '\0';
            if((newbuff[count2] = (char *)malloc(strlen(buffer))) == NULL) {
                printf("MALLOC ERROR!\n");
                exit(-1);
            }
            strcpy(newbuff[count2], ptr);
            printf("\n%s\n",newbuff[count2]);
            ptr = &buffer[count + 1];
            count2 ++;
        }
    }
}

출력은 제가 원하는 것이지만, 마지막 단어 뒤에 공백이 많이 있고, malloc()는 NULL을 반환하기 때문에 마지막에 MALLOC ERROR!이 표시됩니다.malloc() 실장에 오류가 있는 것은 알 수 있지만 무엇인지 모르겠습니다.

좀 더 우아한 방법이 있을까요? 일반적으로 더 나은 방법이 있을까요?

잘 부탁드립니다.

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

여기에서는 공백 문자를 구분자로 사용합니다.힌트가 더 필요하시면 알려주세요.

웹 사이트:

char * strtok ( char * str, const char * delimiters );

첫 번째 콜에서는 첫 번째 문자가 토큰 스캔의 시작 위치로 사용되는 str의 인수로서 C 문자열이 요구됩니다.후속 호출에서는 함수는 늘포인터를 예상하고 마지막 토큰 종료 직후의 위치를 스캔의 새로운 시작 위치로 사용합니다.

strtok에 대한 콜에서 str의 끝 늘 문자가 발견되면 이 함수에 대한 후속 모든 콜(첫 번째 인수로 늘포인터 포함)은 늘포인터를 반환합니다.

파라미터

  • 스트레이트
    • 잘라내는 C 문자열.
    • 이 문자열은 작은 문자열(토큰)로 분할되어 변경됩니다.또는 늘 포인터를 지정할 수 있습니다.이 경우 함수에 대한 이전의 성공한 호출이 종료된 곳에서 함수가 스캔을 계속합니다.
  • 구분자
    • 딜리미터 문자를 포함하는 C 문자열.
    • 이것들은, 콜 마다 다를 수 있습니다.

반환값

문자열에 있는 마지막 토큰에 대한 포인터입니다.검색할 토큰이 남아 있지 않으면 늘 포인터가 반환됩니다.

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

콜백 어프로치에 근거한 실장을 다음에 나타냅니다.

const char* find(const char* s,
                 const char* e,
                 int (*pred)(char))
{
    while( s != e && !pred(*s) ) ++s;
    return s;
}

void split_on_ws(const char* s,
                 const char* e,
                 void (*callback)(const char*, const char*))
{
    const char* p = s;
    while( s != e ) {
        s = find(s, e, isspace);
        callback(p, s);
        p = s = find(s, e, isnotspace);
    }
}

void handle_word(const char* s, const char* e)
{
    // handle the word that starts at s and ends at e
}

int main()
{
    split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}

malloc(0)(선택적으로) 돌아올 수 있다NULL(실장 상황에 따라 다릅니다.왜 전화하셨는지 아세요?malloc(0)더 정확히 말하면, 어레이의 크기를 넘어 읽고 쓰는 곳이 어디인지 알 수 있습니까?

사용을 검토하다strtok_r다른 사람들이 제안했듯이, 또는 다음과 같은 것들이 있습니다.

void printWords(const char *string) {
    // Make a local copy of the string that we can manipulate.
    char * const copy = strdup(string);
    char *space = copy;
    // Find the next space in the string, and replace it with a newline.
    while (space = strchr(space,' ')) *space = '\n';
    // There are no more spaces in the string; print out our modified copy.
    printf("%s\n", copy);
    // Free our local copy
    free(copy);
}

있다get_words()하기 때문에 과 같이하게 됩니다.

char *newbuff[words]; /* Words is one less than the actual number,
so this is declared to be too small. */

newbuff[count2] = (char *)malloc(strlen(buffer))

count2 여러분이 한 개더 많습니다newbuff[]malloc()유효한 PTR을 반환하는 것은 아닙니다만, 잘 모르겠습니다.

strlen(buf)이 아니라 malloc'ing strlen(ptr)이어야 합니다.또한 count2는 단어 수로 제한해야 합니다.문자열 끝에 도달하면 버퍼 내의 0을 계속 검토하여 어레이에 0 크기의 문자열을 추가합니다.

의 다른 스타일의 조작에 소스 C를 하지 않는 입니다.malloc 함수를 strpbrk.

int print_words(const char *string, FILE *f)
{
   static const char space_characters[] = " \t";
   const char *next_space;

   // Find the next space in the string
   //
   while ((next_space = strpbrk(string, space_characters)))
   {
      const char *p;

      // If there are non-space characters between what we found
      // and what we started from, print them.
      //
      if (next_space != string)
      {
         for (p=string; p<next_space; p++)
         {
            if(fputc(*p, f) == EOF)
            {
               return -1;
            }
         }

         // Print a newline
         //
         if (fputc('\n', f) == EOF)
         {
            return -1;
         }
      }

      // Advance next_space until we hit a non-space character
      //
      while (*next_space && strchr(space_characters, *next_space))
      {
         next_space++;
      }

      // Advance the string
      //
      string = next_space;
   }

   // Handle the case where there are no spaces left in the string
   //
   if (*string)
   {
      if (fprintf(f, "%s\n", string) < 0)
      {
         return -1;
      }
   }

   return 0;
}

토큰을 찾은 경우 새 행만 인쇄하면 char 배열을 스캔하고 char를 인쇄할 경우 char를 스캔하면 char 배열을 찾을 수 있습니다.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    int main()
    {
        char *s;
        s = malloc(1024 * sizeof(char));
        scanf("%[^\n]", s);
        s = realloc(s, strlen(s) + 1);
        int len = strlen(s);
        char delim =' ';
        for(int i = 0; i < len; i++) {
            if(s[i] == delim) {
                printf("\n");
            }
            else {
                printf("%c", s[i]);
            }
        }
        free(s);
        return 0;
    }
char arr[50];
gets(arr);
int c=0,i,l;
l=strlen(arr);

    for(i=0;i<l;i++){
        if(arr[i]==32){
            printf("\n");
        }
        else
        printf("%c",arr[i]);
    }

언급URL : https://stackoverflow.com/questions/4513316/split-string-in-c-every-white-space

반응형