c++ - extract digits from filename -
i working file-names in c++. need know how extract part of file-name? file-names like:
/home/xyz/123b45.dat /home/xyz/012b06c.dat /home/xyz/103b12d.dat /home/xyz/066b50.dat i want extract 2 digits after 'b' (45, 06, 12, 50) each file-name , store in array. please suggest how it...
use std::string::find , std::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); } } ( auto & s : parts ) std::cout << s << '\n'; return 0; } ouput input:
$ ./a.out < inp 45 06 12 50 or, if absolutely sure every single line formed, replace inside of loop with:
std::string part = line.substr(line.size()-6, 2); parts.push_back(part); (not recommended).
edit: noticed changed criteria of question, here's replacement loop new criteria:
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); } note of these variations have same output.
you chuck isdigit in there measure too.
final edit: full bpos version, c++98 compatible:
#include <iostream> #include <vector> #include <string> int main() { std::string line; std::vector<std::string> parts; // read available lines. while (std::getline(std::cin, line)) { // find last 'b' in line. std::string::size_type bpos = line.find_last_of('b'); // make sure line reasonable // (has 'b' , @ least 2 characters after) if ( bpos != std::string::npos && line.size() >= bpos+2) { // 2 characters after 'b', std::string. std::string part = line.substr(bpos+1, 2); // push onto vector. parts.push_back(part); } } // prints out vector example, // can safely ignore it. std::vector<std::string>::const_iterator = parts.begin(); ( ; != parts.end(); ++it ) std::cout << *it << '\n'; return 0; }
Comments
Post a Comment