繁体   English   中英

如何在 c 中拆分字符串?

[英]How to split string in c?

我正在尝试使用空格作为分隔符将字符串分成两部分。 我试过下面的代码,但我得到了错误的结果。

#include <stdio.h>
#include <string.h>
void main()
{
    char str_1[5], str_2[5], my_str[] = "hello world";

    //storing hello in str_1.
    for (int i = 0; i <= 4; ++i)
        str_1[i] = my_str[i];
    puts(str_1);

    //storing world in str_2.
    for (int i = 6, j = 0; i <= 10; ++i, ++j)
        str_2[j] = my_str[i];
    puts(str_2);
}

预期 output:

hello
world

获取 output:

hello
worldhello

您必须使用\0终止字符串,并使用 null 字符作为字符串的最后一个字符。 试试下面的代码。

#include <stdio.h>
#include <string.h>
void main()
{
    char str_1[6], str_2[6], my_str[] = "hello world";

    //storing hello in str_1.
    for (int i = 0; i <= 4; ++i)
        str_1[i] = my_str[i];

    str_1[5] = '\0';
    puts(str_1);

    //storing world in str_2.
    for (int i = 6, j = 0; i <= 10; ++i, ++j)
        str_2[j] = my_str[i];

    str_2[5] = '\0';
    puts(str_2);
}

str_1str_2是 char 的 arrays ,您填写数据的方式很好。 但是,当您使用puts()方法时,您必须用'\0'字符标记字符串的结尾,如此链接http://www.cplusplus.com/reference/cstdio/puts/中所述

function 从指定的地址 (str) 开始复制,直到到达终止 null 字符 ('\0')。 此终止空字符不会复制到 stream。

因此,您必须在str_1str_2中为空终止字符添加一个位置:

char str_1[6], str_2[6], my_str[] = "hello world";

然后将子字符串复制到那些 arrays 后,将 '\0' 放在最后复制的字符之后,如下所示:

//storing hello in str_1.
int i;
for (i = 0; i <= 4; ++i) {
    str_1[i] = my_str[i];
}

str_1[i] = '\0';

另一个简单的例子,例如使用strtok()

首先确保变量包含足够的空间用于任务:

 //char str_1[5], str_2[5], my_str[] = "hello world";//need minimum of 6 for each 5 char word
 //           ^         ^
 char str_1[6], str_2[6], my_str[] = "hello world";
 //         ^         ^      
 char *tok = strtok(my_str, " ");
 if(tok)
 {
     strcpy(str_1, tok);
     tok = strtok(NULL, " ");
     if(tok)
     {
         strcpy(str_2, tok);//Note - strcpy terminates target with NULL.
     }
 }

代码中有一些基本错误。请go到c盯着相关理论。 请通过代码和注释 go。

  • 凝视应始终以 '\0' (空字符)结尾。
  • 字符数组大小应始终为字符串的 +1。
#include <stdio.h>
#include <string.h>
void main()
{
    /* array side should be (staring size + 1) here 1 is for staring terminator ('\0') */
    char str_1[6], str_2[6], my_str[] = "hello world";
    int i =0, j =0;
    //storing hello in str_1.
    for (i = 0; i <= 4; ++i)
        str_1[i] = my_str[i];
    /* You need to add null terminator ('\0') at the end of the staring so that we can print it properly */
    str_1[i] = '\0';
    puts(str_1);

    //storing world in str_2.
    for (i = 6, j = 0; i <= 10; ++i, ++j)
        str_2[j] = my_str[i];
    /* You need to add null terminator ('\0') at the end of the staring so that we can print it properly */
    str_2[j] = '\0';
    puts(str_2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM