C 字符串和子字符串

C 字符串和子字符串,c,string,substring,C,String,Substring,我尝试使用不同的版本,但它们都不能正常工作。这就是我在这里发帖的原因。我需要返回两个字符串的数组。第一个是从头到尾的子字符串,但不包括逗号。第二个是逗号后s的子字符串。字符串只包含一个逗号。我还需要使用char*strrconst char*s,intc。嗯,这对我没有帮助。请帮我,花了很多时间…谢谢 #include <stdio.h> #include <stdlib.h> #include <string.h> char **spli

我尝试使用不同的版本,但它们都不能正常工作。这就是我在这里发帖的原因。我需要返回两个字符串的数组。第一个是从头到尾的子字符串,但不包括逗号。第二个是逗号后s的子字符串。字符串只包含一个逗号。我还需要使用char*strrconst char*s,intc。嗯,这对我没有帮助。请帮我,花了很多时间…谢谢

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

   char **split_on_comma(const char * s){




   //this piece of code does not work
   /*int i;
   char array[80];

    for (i=0; i<strlen(s)-1; i++){
       if(substr=(s[i],',')==NULL){
        array[i]=s[i];
      } else
  }*/

  return 0;
  }

这很简单:只需复制字符串的两半

char **split_on_comma(const char *str)
{
    const char *p = strchr(str, ',');
    if (p == NULL)
        return NULL;

    char **subs = malloc(2 * sizeof subs[0]);
    ptrdiff_t len1 = p - str;
    ptrdiff_t len2 = str + strlen(str) - (p + 1);

    // copy and 0-terminate first half
    subs[0] = malloc(len1 + 1);
    memcpy(subs[0], str, len1);
    subs[0][len1] = 0;

    // copy and 0-terminate second half
    subs[1] = malloc(len2 + 1);
    memcpy(subs[1], p + 1, len2);
    subs[1][len2] = 0;

    return subs;
}

为清楚起见,省略了对malloc返回NULL的检查,但应包含在生产代码中。

请描述您预期会发生什么以及正在发生什么?提示strhr,*p='\0';研究同一问题的人@曼纽尔什么是谷歌?那些无关的问号是什么?我不是聋子!