美文网首页
C++ 切分字符串

C++ 切分字符串

作者: louyang | 来源:发表于2019-04-04 15:05 被阅读0次
问题:

有这样一种字符串:

<prefix>-<index>

index是整数,prefix是任意字符串,例如:

abc-def-20

请写一段代码,把prefix和index分开:

解答:

#include <string>
#include <iostream>

int main()
{
    std::string a {"abc-def-20"};
    std::size_t found = a.find_last_of("-");
    std::cout << a.substr(0,found) << std::endl;
    int i = std::stoi(a.substr(found+1));
    std::cout << i << std::endl;
}
$ g++ a.cpp && ./a.out
abc-def
20

相关文章

网友评论

      本文标题:C++ 切分字符串

      本文链接:https://www.haomeiwen.com/subject/nqzfiqtx.html