【问题标题】:How can I efficiently split strings and copy substrings in C?如何在 C 中有效地拆分字符串和复制子字符串?
【发布时间】:2020-01-09 18:55:02
【问题描述】:

我曾经通过多种方式拆分 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);

【问题讨论】:

  • strtokstrsep 是通常的方式。
  • C 是低级语言,一切都是冗长而笨拙的。
  • 以前大家都说C是低级的,我不明白,现在我想明白了
  • C 不附带训练轮。它会很高兴地让您向数组写入比分配更多的元素,等等......这就是让 C 如此快速的原因,也是准确计算所使用内存的每个字节的原因——程序员的责任.. ..

标签: c string split


【解决方案1】:

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

您的代码可以简化为:

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

char *delimiter_location = strstr(message, "...");
int m1_strlen            = delimiter_location - message;

// Not every C standard and every compiler supports dynamically sized arrays.
// In those cases you need to use malloc() and free().
// Or even better: strdup() or strndup().
char message_1[m1_strlen + 1];
// NB no need to call memset() because the space is written to immediately:
strncpy(message_1, message, m1_strlen);
message_1[m1_strlen] = '\0'; // This ensures a terminated string.

printf("message: %s\n", message);
printf("message 1: %s\n", message_1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2019-10-11
    • 1970-01-01
    • 2012-02-14
    • 2021-12-07
    • 2017-01-14
    相关资源
    最近更新 更多