如何在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," "));
智能推荐

注意!

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



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

赞助商广告