Best way to get ints from a string with whitespace?

后端 未结 5 929
挽巷
挽巷 2020-12-08 22:30

I know this is simple, I just can\'t recall the best way to do this. I have an input like \" 5 15 \" that defines the x and y of a 2D vector array. I simply ne

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 23:05

    The C++ String Toolkit Library (StrTk) has the following solution to your problem:

    int main()
    {
       std::string input("5 15");
       int col = 0;
       int row = 0;
       if (strtk::parse(input," ",col,row))
          std::cout << col << "," << row << std::endl;
       else
          std::cout << "parse error." << std::endl;
       return 0; 
    }
    

    More examples can be found Here

    Note: This method is roughly 2-4 times faster than the standard library routines and rougly 120+ times faster than STL based implementations (stringstream, Boost lexical_cast etc) for string to integer conversion - depending on compiler used of course.

提交回复
热议问题