【问题标题】:Having issues splitting strings when using the strsep function使用 strsep 函数时拆分字符串时出现问题
【发布时间】:2023-01-11 23:24:26
【问题描述】:

我是 C 编程的新手,并试图使用 strsep 函数通过它的分隔符拆分字符串。

执行下面的代码时,我得到以下输出:

Hostname ( teste-13-f8-04teste-13-fd-80) Hostname (teste-13-fd-80) Hostname (teste-13-fd-86) Hostname (teste-13-fd-90)

为什么 AllHostName[0] 给出了那个输出?

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

void splitStrings(char splitString[] , char variable[][15]);

void splitStrings(char splitString[] , char variable[][15])
    {
        char *token, *str, *tofree;
        int i=0;
        tofree = str = strdup(splitString);
        while ((token = strsep(&str, ",")))
            {
                strcpy(variable[i], token);
                i++;
            }
    free(tofree);
    }

int main(){
            char HostName[] = " teste-13-f8-04,teste-13-fd-80,teste-13-fd-86,teste-13-fd-90";
            char AllHostName[32][15];
            splitStrings(HostName, AllHostName);
            printf(" Hostname (%s) Hostname (%s) Hostname (%s) Hostname (%s)\n" , AllHostName[0] , AllHostName[1],AllHostName[2],AllHostName[3]);
           }

收到此错误后,我注意到它与原始字符串的大小有关,如果字符串较小,则不会出现此问题。

【问题讨论】:

  • 一致的缩进将使您的代码更具可读性。
  • 您的 char AllHostName[32][15] 太小了,请将 15 更改为更大的数字并使用 strncpy() 而不是 strcpy()
  • 不过,@MarcoBonelli 小心 strncpy()。它也不能保证终止'\0'
  • 真的想要第一个字符串开头的那个空格吗?

标签: arrays c string memory strsep


【解决方案1】:

中的第一个令牌

char HostName[] = " teste-13-f8-04,teste-13-fd-80,teste-13-fd-86,teste-13-fd-90";

teste-13-f8-04

这是 15 个字符长,对于16字符标记(其中包括终止 '

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2020-08-11
  • 2018-11-21
  • 1970-01-01
相关资源
最近更新 更多