如何有效地在C中拆分字符串并复制子字符串?

时间:2019-09-07 00:17:41

标签: c string split

我曾经用多种方式分割C字符串:strstr,strsep,strtok,strtok_r ...在这种情况下,我有一个定界符,我想分割字符串。仅在Java,JavaScript,Python等语言中这样做,才显得冗长而笨拙。感觉有点脆弱。是否有更好的方法来做到这一点?我觉得我对算术非常信任。

  char message []      = "apples are better than bananas...But good as grapes?";

  char *delimiter_location   = strstr(message, "...");
  int m1_strlen        = delimiter_location - message;
  int m1_chararr_size  = m1_strlen + 1;
  char message_1 [m1_chararr_size];
  memset(message_1, '\0', m1_chararr_size);
  strncpy(message_1, message, m1_strlen);
  printf("message: %s\n", message);
  printf("message 1: %s", message_1);

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式库,例如discussed here

您的代码可以简化为:

function a() {
  var myA = 'this is parent Fn';
  var anotherFn = function b() {
    var add = myA + ' and this is writen from inside Function!';
    console.log(add);
  }
  anotherFn()
}

a();