繁体   English   中英

根据 \n 将 char 数组分成几部分

[英]Breaking a char array into parts based on \n

这是我在堆栈上的第一个问题,我是 c 的初学者。我声明了一个 char 数组 a[100]={“这是一个测试\n第二次测试}。现在我正在尝试划分这个数组并取两个部分在 \n 之前和之后作为单独的字符串。所以我声明了一个二维数组 ab[i][k] 并使用 for 循环将字符复制到 ab[i]。如果 a[j]=='\n',我在 ab[i][k] 的当前 position 处放置一个 NULL 字符并将 i 增加 1。但由于某种原因,当我使用 ZAFA7ZFF8B27B15ABDE57666 时,ab[0] 和 ab[1] 都显示“这是一个测试”显示它们。任何帮助或建议将不胜感激。

int i=0; 
char a[100],ab[100][100],c;
fputs(a,stdout);
printf("%d ",strlen(a));
for(j=0;j<=strlen(a);j++,k++)
{
    if(a[j]=='\n')
    {
        ab[i][k]='\0';
        k=0;
        i++;
        continue;
    }
    ab[i][k]=a[j];
}
printf("%s\n",ab[0]);
printf("%s",ab[1]);

您需要设置k=-1; 当您找到\n时,因为当您continue;时它将在循环顶部递增到0 .

您还需要声明int j, k=0; 在循环之前,让你的代码编译。


#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

int main(int argc, char const *argv[]) {
    int i=0;
    char ab[100][100];

    char a[100] = "this is a test\n2nd test";
    printf("%d \n",strlen(a));

    int j, k=0;
    for(j=0; j<=strlen(a); j++,k++) {
        if(a[j]=='\n') {
            ab[i][k]='\0';
            k=-1;
            i++;
            continue;
        }
        ab[i][k]=a[j];
    }

    printf("1: %s\n",ab[0]);
    printf("2: %s\n",ab[1]);

    return 0;
}
23
1: this is a test
2: 2nd test
#include <stdio.h>
#include <stdlib.h>
#include <string.h> 

int main(int argc, char const *argv[])
{
    char ar[100] = "this is a test\n2nd test\nfoobar\netc";
    char sep[10][100];

    int i=0;
    char* token = strtok(ar, "\r\n");
    while(token != NULL) { 
        sprintf(sep[i], "%s", token);
        printf("string #%02i: `%s`.\n", i, sep[i]);
        token = strtok(NULL, "\r\n");
        i++;
    }

    return 0;
}

strtok()通过作为分隔符传递的任何字符(在本例中为新行和回车)将字符串拆分为标记。 将 null 指针传递给 function 继续上次停止的地方。 它返回一个指向令牌开头的指针,

sprintf()将格式化数据保存到为您处理 \0 的变量中,但如果您愿意,也可以使用memcpy()strcpy()

暂无
暂无

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

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