programing

C에서 문자열을 2개의 문자열로 분할하는 방법

telebox 2023. 7. 6. 22:09
반응형

C에서 문자열을 2개의 문자열로 분할하는 방법

어떻게 1개의 문자열을 가져다가 공백과 같은 구분 기호로 2개로 나누고 2개의 부분을 2개의 별도 문자열에 할당할 수 있는지 궁금합니다.사용해 보았습니다.strtok()하지만 소용이 없습니다.

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);

갱신하다

일부 운영 체제에서는strtok맨 페이지 언급:

이 인터페이스는 strsep(3)에 의해 사용되지 않습니다.

의 예strsep아래에 나와 있습니다.

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

  tofree = string;

  while ((token = strsep(&string, ",")) != NULL)
  {
    printf("%s\n", token);
  }

  free(tofree);
}

이와 같은 목적을 위해 저는 strtok() 대신 strtok_r()을 사용하는 경향이 있습니다.

예를 들어...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

그러면 출력...

'''123456''' '''789 asdf'''

더 많은 구분 기호가 필요한 경우 루프합니다.

이게 도움이 되길 바랍니다.

char *line = strdup("user name"); // don't do char *line = "user name"; see Note

char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " ");   //sec_part points to "name"

참고:strtok문자열을 수정하므로 포인터를 문자열 리터럴에 전달하지 마십시오.

strtok()을 사용할 수 있습니다. 예: 저에게 적합합니다.

#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;
}

할당된 문자 배열이 있는 경우에는 간단히'\0'당신이 원하는 곳 어디든지.그런 다음 새 문자 * 포인터를 새로 삽입한 직후의 위치로 가리킵니다.'\0'.

이것은 당신이 어디에 두었는지에 따라 당신의 원래 문자열을 파괴할 것입니다.'\0'

원래 문자열을 변경할 수 있는 경우 구분 기호를 다음으로 바꿀 수 있습니다.\0원래 포인터는 첫 번째 문자열을 가리키고 구분 기호가 두 번째 문자열을 가리킨 후 문자를 가리킵니다.좋은 점은 새로운 문자열 버퍼를 할당하지 않고도 두 포인터를 동시에 사용할 수 있다는 것입니다.

할 수 있는 일:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

두 개 이상의 토큰을 기대하는 경우 두 번째 및 이후 통화를 호출하는 것이 좋습니다.strtok의 반환 값이 나올 때까지 잠시 루프에서strtok된다NULL.

다음과 같이 구현할 수 있습니다.strtok()(zString이라고 하는 C용 BSD 라이센스 문자열 처리 라이브러리에서 가져온) like 함수.

아래 기능이 표준과 다름strtok()연속적인 구분자를 인식하는 방식에서, 반면 표준은.strtok()하지 않다.

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

다음은 사용법을 보여주는 코드의 예입니다.

  Example Usage
      char str[] = "A,B,,,C";
      printf("1 %s\n",zstring_strtok(s,","));
      printf("2 %s\n",zstring_strtok(NULL,","));
      printf("3 %s\n",zstring_strtok(NULL,","));
      printf("4 %s\n",zstring_strtok(NULL,","));
      printf("5 %s\n",zstring_strtok(NULL,","));
      printf("6 %s\n",zstring_strtok(NULL,","));

  Example Output
      1 A
      2 B
      3 ,
      4 ,
      5 C
      6 (null)

시간 루프(표준 라이브러리)를 사용할 수도 있습니다.strtok()여기서 동일한 결과를 제공합니다.)

char s[]="some text here;
do {
    printf("%s\n",zstring_strtok(s," "));
} while(zstring_strtok(NULL," "));

언급URL : https://stackoverflow.com/questions/2523467/how-to-split-a-string-to-2-strings-in-c

반응형