微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Typedef Struct创建函数以返回拆分字符串数组

如何解决如何使用Typedef Struct创建函数以返回拆分字符串数组

解决练习时,我坚持使用内存分配。本练习的目的是创建一个使用两个参数的函数(例如,“ abc def gh-!”和&“-”),方法是使用分隔符(在本例中为第二个参数)分隔字符串,然后返回一个在我的typedef结构中,其中包含新的拆分字符串。

到目前为止,这是我的代码...

    #ifndef STRUCT_STRING_ARRAY
#define STRUCT_STRING_ARRAY
typedef struct s_string_array
{
    int size;
    char** array;
} string_array;
#endif

string_array* my_split(char* str,char* sep) {

  string_array*ptr=(string_array*)malloc(sizeof(string_array)); //Memory allocation Struct

  int i;
  int j;
  int words;
  int in_word;

  i = 0;
  words = 1;

  while (str[i]) {
      if (str[i] != *sep) {
          if (!in_word) {
              words++; // Count number of words inside the string
          }
          in_word = 1;
      } else {
          in_word = 0;
      }
      i++;
  }
  ptr->size = words;
  ptr->array=malloc(sizeof(char*)*ptr->size); // Allocate the array of pointer inside struct

  int size = 0;
  i = 0;
  j = 0;
  while (i < ptr->size)  {
      while (str[j] != *sep) {
          size++;
          j++;
      }
      ptr->array[i]=malloc(sizeof(char) * (size + 1));
      ptr->array[i][size+1] = '\0';
    i++;
  }

  int c = 0;
  int r = 0;
  i = 1;
  j = 0;

  while (i < ptr->size) {
      if (str[j] != *sep) {
          while (str[j] != *sep) {
              ptr->array[c][r++] = str[j++];
          }
      }
      i++;
      c++;
  }
  printf("%s\n",ptr->array[0]);
  printf("Words in new Array is: %d\n",ptr->size);
  printf("J is at index: %d\n",j);
  printf("The character at index J is: %c\n",str[j]);
  printf("The first index of the array is Now at: %d\n",c);
}

int main() {
    my_split("abc def gh-!","-");
    return 0;
}

返回值必须为:[“ abc def gh”,“!”]

请帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。