【问题标题】:Extract int value and string from string [closed]从字符串中提取int值和字符串[关闭]
【发布时间】:2018-05-13 22:00:05
【问题描述】:

我想使用字符串类,从字符串中提取一些信息。 给定字符串:,,

我想让 12、20、49 变成一个 int 数组。 这意味着 a[0] = 12,a[1] = 20,a[2] = 49。

并让 Apple、Orange、iPhone 成为一个 String 数组。 这意味着 b[0] = "Apple", b[1] = "Orange" b[2] = "iPhone"

我该怎么办?

【问题讨论】:

  • 我的伪代码能帮助你理解你应该做什么吗?基本上你需要提取每个标点位置,然后使用这些位置提取字符串。如果字符串的值为整数,可以使用atoi函数将字符串转换为整数

标签: c++ arrays string integer


【解决方案1】:

假设字符串遵循格式<int,string>,...。请在下面找到伪代码:

Loop through the string `str` and
{
    smaller_sign_pos = str.find('<', prev_pos)
    entry_comma_pos = str.find(',', smaller_sign_pos+1)
    greater_sign_pos = str.find('>', entry_comma_pos+1)

    if (all pos values are not `npos`)
    {
        int_value = atoi(str.substr(smaller_sign_pos+1, entry_comma_pos-smaller_sign_pos-1))
        str_value = str.substr(entry_comma_pos+1, greater_sign_pos-entry_comma_pos-1)
        prev_pos = greater_sign_pos+1
        append int_value to int array
        append str_value to string array
        optional: you can check if the comma after '>' exists
    }
    else
    {
        break or set the end of loop flag
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多