如何在C中將一個字符串分割成兩個字符串

[英]How to split a string to 2 strings in C


I was wondering how you could take 1 string, split it into 2 with a delimiter, such as space, and assign the 2 parts to 2 separate strings. I've tried using strtok() but to no avail.

我想知道如何取1個字符串,將它分成2個分隔符,比如空格,然后將2個部分分配給2個單獨的字符串。我試過使用strtok(),但沒有用。

8 个解决方案

#1


55  

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

Update

Note that on some operating systems, strtok man page mentions:

注意,在某些操作系統上,strtok man頁面提到:

This interface is obsoleted by strsep(3).

這個接口被strsep(3)廢棄。

An example with strsep is shown below:

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

#2


10  

For purposes such as this, I tend to use strtok_r() instead of strtok().

出於這樣的目的,我傾向於使用strtok_r()而不是strtok()。

For example ...

例如……

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

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

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

This will output ...

這將輸出……

'123456' '789asdf'

“123456”“789 asdf”

If more delimiters are needed, then loop.

如果需要更多的分隔符,那么循環。

Hope this helps.

希望這個有幫助。

#3


3  

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"

Note: strtok modifies the string, so don't hand it a pointer to string literal.

注意:strtok修改了字符串,所以不要給它一個指向字符串文字的指針。

#4


3  

You can use strtok() for that Example: it works for me

對於這個例子,您可以使用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;
}

#5


1  

If you're open to changing the original string, you can simply replace the delimiter with \0. The original pointer will point to the first string and the pointer to the character after the delimiter will point to the second string. The good thing is you can use both pointers at the same time without allocating any new string buffers.

如果您願意更改原始字符串,可以簡單地用\0替換分隔符。原始指針將指向第一個字符串,分隔符之后指向字符的指針將指向第二個字符串。好在您可以同時使用這兩個指針,而無需分配任何新的字符串緩沖區。

#6


1  

If you have a char array allocated you can simply put a '\0' wherever you want. Then point a new char * pointer to the location just after the newly inserted '\0'.

如果分配了一個char數組,您可以在任何需要的地方放置一個'\0'。然后在新插入的“\0”之后,將一個新的char *指針指向該位置。

This will destroy your original string though depending on where you put the '\0'

這將破壞你原來的字符串,盡管這取決於你把'\0'放在哪里

#7


1  

You can do:

你能做什么:

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

If you expect more than one token its better to call the 2nd and subsequent calls to strtok in a while loop until the return value of strtok becomes NULL.

如果您期望不止一個令牌,那么最好在一個while循環中調用strtok的第二個和后續調用,直到strtok的返回值變為NULL。

#8


1  

This is how you implement a strtok() like function (taken from a BSD licensed string processing library for C, called zString).

這就是如何實現類似strtok()的函數(取自BSD許可的C字符串處理庫,名為zString)。

Below function differs from the standard strtok() in the way it recognizes consecutive delimiters, whereas the standard strtok() does not.

下面的函數在識別連續分隔符的方式上與標准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;
}

Below is an example code that demonstrates the usage

下面的示例代碼演示了這種用法

  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)

You can even use a while loop (standard library's strtok() would give the same result here)

您甚至可以使用while循環(標准庫的strtok()將在這里給出相同的結果)

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/03/26/7203da04e19603f9c82610d4f19256a9.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com