【问题标题】:split strings using c language使用c语言分割字符串
【发布时间】:2012-12-19 10:25:58
【问题描述】:

我有一个包含以下行的文件:

0: 1(ab) 6(a)
1: 3(b) 4(a)
2: 5(a) 3(ab)

我想拆分这些行以获取值,并以某种方式将它们存储在数组或其他东西中。

任何帮助!

More Explanations

0、1、2 是图形的峰值。

对于第一个峰值 0,我们有两条弧线 1 和 6,圆括号中的值是弧线的值。

【问题讨论】:

  • 搜索strtokstrchr
  • 阅读fscanf 的文档,可能会有所帮助。

标签: c string split


【解决方案1】:

fscanf 似乎工作正常,正如@Adeel 建议的那样:-

#include<stdio.h>

int main()
{
    int peak, arc1, arc2;
    char v1[100], v2[100];
    scanf("%d: %d(%s %d(%s", &peak, &arc1, &v1, &arc2, &v2);
    v1[strlen(v1)-1] = 0; // clear the closing parentheses
    v2[strlen(v2)-1] = 0; // clear the closing parentheses

    printf("%d, %d, %s, %d, %s", peak, arc1, v1, arc2, v2);
}

需要清除,因为字符串被读取 1 太远。如果输入没有任意空格,这将起作用。对于这些情况,可能需要 strtok 等。

已测试:-

C:\Users\user\Desktop>test.exe
0: 1(ab) 6(a)

输出:-

0, 1, ab, 6, a

【讨论】:

  • 在这种情况下,您需要更好的东西。就像@joachim 建议的那样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 2015-12-09
  • 1970-01-01
  • 2022-09-28
  • 2015-01-21
  • 2012-03-18
相关资源
最近更新 更多