c++ - 从文件名中提取数字

标签 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)并将其存储在数组中。有人可以建议如何做吗...

最佳答案

使用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;
}

关于c++ - 从文件名中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16562650/

相关文章:

c++ - C++ 代码的探查器,非常困

c++ - Qt客户端程序

c++ - 当类包含虚方法时,为什么 clang 会创建这些隐式方法?

python - Python中的目录树列表

java - 在 C++ 中重新加载 Java 字符串

javascript - js代码在外部文件中不起作用,但放在同一个html页面中时可以工作

Java InputStreamReader 无法读取特殊(土耳其语)字符

linux - 存储由名称中带有空格的文件组成的 ls 命令的输出

regex - 查找文件夹中编号最大的文件名

Git复制文件保存历史