字符串和子串

时间:2014-10-24 18:52:48

标签: c string substring

我尝试使用不同的版本,但所有这些都不能正常工作。这就是我在这里发帖的原因。我需要返回一个包含两个字符串的数组。第一个是从头到尾的子串,但不包括逗号。第二个是逗号后面的s子串。字符串只包含一个逗号。另外我需要使用char * strchr(const char * s,int c)。好吧,它没有帮助我。请用这个帮忙,花了很多时间......谢谢

#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;
  }

1 个答案:

答案 0 :(得分:2)

这非常简单:只需复制字符串的两半即可。

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的检查被省略,但仍应包含在生产代码中。