繁体   English   中英

如何从C中以null分隔的char数组中读取字符串?

[英]How to read strings from char array separated by null in c?

我有一个char数组,其中包含用null分隔的字符串。 我有char aarray中存在的字符串的索引。 如何使用索引从此char数组读取字符串,并以null分隔。

例如我有以下字符数组,

char *buf = ['\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0'];

我有这些字符串的索引,例如bcs字符串的索引1, 字符串的索引5, nxt字符串的索引9

如何从这个char数组中使用索引读取这些字符串?

很抱歉,我得到了答案,我们可以从char数组中获取字符串,如下所示:-获取要获取的字符串的索引地址-打印字符串

char* str = &buf[index];
if(str)
printf("string is : %s\n", str);

一种更通用的方法是遍历buf直到您打印了所有字符串,即不使用索引。

然后的问题是如何识别缓冲区(已使用部分)的结尾。 一个通用的技巧是使用额外的空字符终止缓冲区。 以下内容说明了这一点:

char buf[] = {'\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0', '\0'};

void f(void)
{
    char *s= buf;
    do {
        if (*s==0) {
            if (*(s+1)==0) break;
            s++;
        }
        puts(s);
        while (*s) s++;
    } while(1);
}

这是您的操作方法。虽然我没有进行任何安全检查,但是代码仅显示了如何从以空终止符分隔的字符数组中读取字符串。每当您为数组分配多个值时,请使用方括号[]而不是使用大括号 {}

#include <stdio.h>
int main(void) {
   char buf[] = {'\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0'};
   int indx = 0;
   printf("Which index to read from:");
   scanf("%d", &indx);
   for(int i = indx; buf[i] != '\0'; i++){
    printf("%c", buf[i]);
  }
}

暂无
暂无

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

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