C语言 如何在C中将字符串拆分为2个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2523467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string to 2 strings in C
提问by Mark Szymanski
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()但无济于事。
回答by ereOn
#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, strtokman page mentions:
请注意,在某些操作系统上,strtok手册页提到:
This interface is obsoleted by strsep(3).
此接口已被 strsep(3) 废弃。
An example with strsepis 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);
}
回答by Sparky
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' '789asdf'
If more delimiters are needed, then loop.
如果需要更多分隔符,则循环。
Hope this helps.
希望这可以帮助。
回答by N 1.1
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: strtokmodifies the string, so don't hand it a pointer to string literal.
注意:strtok修改字符串,所以不要给它一个指向字符串文字的指针。
回答by mkafkas
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;
}
回答by Mehrdad Afshari
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. 原始指针将指向第一个字符串,而指向分隔符后字符的指针将指向第二个字符串。好处是您可以同时使用两个指针,而无需分配任何新的字符串缓冲区。
回答by Brian R. Bondy
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'.
如果你分配了一个字符数组,你可以简单地把一个放在'\0'任何你想要的地方。然后将一个新的 char * 指针指向新插入的'\0'.
This will destroy your original string though depending on where you put the '\0'
这将破坏您的原始字符串,但这取决于您放置的位置 '\0'
回答by codaddict
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 strtokin a while loop until the return value of strtokbecomes NULL.
如果您希望有多个标记,最好strtok在 while 循环中调用第二次和后续调用,直到 的返回值strtok变为NULL。
回答by fnisi
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] = ' 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)
';
/* 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
下面是演示用法的示例代码
char s[]="some text here;
do {
printf("%s\n",zstring_strtok(s," "));
} while(zstring_strtok(NULL," "));
You can even use a while loop (standard library's strtok()would give the same result here)
您甚至可以使用 while 循环(标准库strtok()会在这里给出相同的结果)

