【问题标题】:How do I cut up string using a delimiter (space) just like substr in php?如何使用分隔符(空格)分割字符串,就像 php 中的 substr 一样?
【发布时间】:2013-03-30 04:03:33
【问题描述】:

这是我的Mystr 值:

其他:0.01 罚款:0.02 pdi:0.03 pdp:0.04 利息:0.05 本金:0.06 cbu:0.07 储蓄:0.08 银行手续费:0.09 grt:0.10

我想要的输出:

其他:0.01

罚分:0.02

pdi:0.03

pdp:0.04

兴趣:0.05

本金:0.06

cbu:0.07

节省:0.08

银行手续费:0.09

grt:0.10

我希望将其分配给不同的变量。我该怎么做?

【问题讨论】:

  • 您正在寻找strtok 或strsep。 strsep 更好,但不便携。
  • 谢谢你的回答..它有很大帮助..

标签: c char substring delimiter substr


【解决方案1】:

C 中的工具是 strtok(GNU Manual, SUS V2 Spec)。您第一次调用 strtok 时设置了字符串和分隔符。然后,对于后续部分,调用 strtok 并设置 NULL 和分隔符,它将继续从中断的位置开始搜索。

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

int main(void) {
    char x[] = "others:0.01 penalty:0.02 pdi:0.03 pdp:0.04 interest:0.05 principal:0.06 cbu:0.07 savings:0.08 bankcharge:0.09 grt:0.10";
    char toPrint[sizeof(x) * 2];
    char *a;

    strcpy(toPrint,strtok(x," "));
    strcat(toPrint,"\n");

    while ((a=strtok(NULL," ")) != NULL) {
        strcat(toPrint,a);
        strcat(toPrint,"\n");
    }
    fputs(toPrint,stdout);
}

打印

others:0.01
penalty:0.02
pdi:0.03
pdp:0.04
interest:0.05
principal:0.06
cbu:0.07
savings:0.08
bankcharge:0.09
grt:0.10

注意strtok 修改了原始数组。在程序结束时,x 数组包含"1\02\03\04"。所有分隔符都被零覆盖。另请注意,字符串中的两个连续分隔符将导致strtok 为(缺失)值生成一个空字符串""。

【讨论】:

  • 如果有一个链接作为参考,也许还有一个用户示例=)
  • 谢谢你的回答..我现在才知道它们是一个函数,就像 php 中的 substr 一样..美好的一天,祝福的一天..
  • 明白。在 C 中制作子串的集合将是 2 或 3 个“蠕虫罐头”! :)
  • 顺便说一句,我如何分配使用 strtok.. int main() { char str[] = "penalty:0.01 pdi:0.02 pdp:0.03";字符 * pch; pch = strtok (str," "); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " "); } 返回 0; }
  • 这就是我提到的蠕虫罐。这是很多工作。最简单的方法是拥有一个指针数组,然后将指针保存在数组中。如果您无法预测数组的最大大小并且需要realloc 以获得更多空间,这将变得很棘手。另一种选择是链表。
【解决方案2】:

如果您使用 Python 编写代码,您会很幸运使用 split()。 在 C 语言中,您可以使用 strtok http://www.cplusplus.com/reference/cstring/strtok/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多