从文件名中提取数字

时间:2013-05-15 10:28:40

标签: c++ file filenames

我正在使用C ++中的文件名。我需要知道如何提取文件名的某些部分? 文件名如下:

/home/xyz/123b45.dat

/home/xyz/012b06c.dat

/home/xyz/103b12d.dat

/home/xyz/066b50.dat

我想从每个文件名中提取'b'(45,06,12,50)之后的两位数并存储在数组中。有人可以建议怎么做......

2 个答案:

答案 0 :(得分:5)

使用std::string::findstd::string::substr

int main()
{
    std::string line;
    std::vector<std::string> parts;
    while (std::getline(std::cin, line))
    {
        auto suffix = line.find(".dat");
        if ( suffix != std::string::npos && suffix >= 2)
        {
            std::string part = line.substr(suffix-2, 2);
            parts.push_back(part);
        }
    }

    for ( auto & s : parts )
        std::cout << s << '\n';

    return 0;
}

输入输出:

$ ./a.out < inp
45
06
12
50

或者,如果你绝对确定每一行都是格式良好的,你可以用以下代码替换循环内部:

std::string part = line.substr(line.size()-6, 2);
parts.push_back(part);

(不推荐)。

修改:我注意到您更改了问题的条件,因此这里是新条件的替换循环:

auto bpos = line.find_last_of('b');
if ( bpos != std::string::npos && line.size() >= bpos+2)
{
    std::string part = line.substr(bpos+1, 2);
    parts.push_back(part);
}

请注意,所有这些变体都具有相同的输出。

你也可以在那里放一个isdigit以获得好的评价。

最终修改:这是完整的bpos版本,c++98兼容:

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::string line;
    std::vector<std::string> parts;
    // Read all available lines.
    while (std::getline(std::cin, line))
    {
        // Find the last 'b' in the line.
        std::string::size_type bpos = line.find_last_of('b');
        // Make sure the line is reasonable
        // (has a 'b' and at least 2 characters after)
        if ( bpos != std::string::npos && line.size() >= bpos+2)
        {
            // Get the 2 characters after the 'b', as a std::string.
            std::string part = line.substr(bpos+1, 2);
            // Push that onto the vector.
            parts.push_back(part);
        }
    }

    // This just prints out the vector for the example,
    // you can safely ignore it.
    std::vector<std::string>::const_iterator it = parts.begin();
    for ( ; it != parts.end(); ++it )
        std::cout << *it << '\n';

    return 0;
}

答案 1 :(得分:0)

考虑到问题的标题,我假设您将文件名存储为vectors的{​​{1}}。更好的方法是使用chars s。字符串允许各种设施功能,包括标记化和子串的检索等(这是你想要做的)。

相关问题