[英]Easiest way to tokenize/split a string using string delimiters?
好的,我承认在C ++方面,字符串操作从来都不是我的强项,尽管仅在使用Boost的情况下,我在各种情况下都取得了成功,但仍然存在一些问题。
所以,这就是我需要的(示例很精确)...
输入是:
position fen <arg_a1> <arg_a2> ... <arg_aN> moves <arg_b1> <arg_b2> ... <arg_bN>
(嗯,对于那些熟悉该主题的人,这是UCI协议的命令)
我要做的就是:
<arg_a1> <arg_a2> ... <arg_aN>
(包括空格)分成一个字符串(即position
和moves
之间的字符串) <arg_b1> <arg_b2> ... <arg_bN>
放入另一个字符串(即从moves
到结尾的字符串)。 我在Boost::split
玩了很多,但是显然,它的工作方式与strtok
相似(接受字符而不是字符串定界符)。
我该怎么办? 在不重新发明轮子的情况下解决这个特定问题的最简单方法是什么(我经常这样做……经常……大声笑)?
提示:显然我可以做到。 但是我现在所能想到的只是非常丑陋。 我正在寻找的是一种C ++友好的方式...
这是解决方案 (带有一些数字技巧):
// where are 'fen' and 'moves' within the initial string?
int fenPos = input.find("fen");
int movesPos = input.find("moves");
// get the exact string but taking into account the position of our initial tokens
// as well as their length (e.g. fenPos.length()+1 = 4, etc)
string fen = input.substr(fenPos+4,movesPos-fenPos-5);
string moves = input.substr(movesPos+6);
所以输入:
"position fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 moves f2f3 e7e6 g2g4"
,返回:
fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
moves = "f2f3 e7e6 g2g4"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.