我需要获得一个字符串的一部分,但是' round'削减到下一个确切的字符','避免坏切; 这个例子更加明确:
string hand = "AA,KK,QQ,JJ,AKs,AKo,AQs,AQo,TT,AJs,ATs,AJo,KQs,KJs,KTs,QJs,ATo,QTs,JTs,A9s,A9o,KQo,A8s,A8o,A7s,A7o,A6s,A6o,A5s,A5o,A4s,99,A4o,A3s,A2s,KJo,J9s,T9s,Q9s,QJo,KTo,Q9o,88,77,66,QTo,A3o,A2o,JTo,K9s,K8s,K7s,K6s,K5s,K4s,K3s,K2s,Q8s,Q7s,Q6s,Q5s,K9o,J8s,T8s,98s,97s,87s,86s,76s,96s,75s,65s,64s,J9o,T9o,55,54s,53s,52s,K8o,43s,32s,42s,J7s,T7s,K7o,44,33,22,Q4s,Q3s,Q2s,J6s,J5s,T6s,T5s,J4s,K6o,Q8o,J8o,T8o,98o,97o,87o,85s,K5o,K4o,K3o,K2o,95s,74s,76o,65o,54o,84s,94s,Q7o,J7o,T7o,Q6o,J3s,T4s,J2s,Q5o,T3s,T2s,Q4o,J6o,86o,T6o,96o,93s,Q3o,74o,84o,75o,64o,T2o,94o,53o,93o,63o,43o,92o,73o,83o,52o,82o,42o,62o,72o,J5o,63s,92s,73s,Q2o,J4o,83s,85o,82s,T5o,95o,J3o,62s,T4o,J2o,72s,T3o,32o";
手的长度是662。我想得到让我们说第7%的弦手:
int startpos = 0;
int stoppos= (662 * 7) / 100;
string str2 = hand.substr(startpos, stoppos);
cout << str2 << endl;
这将输出 KTs,QJs,A
正如你所看到的那样,最后一手牌被切断了,所以我想把下一个昏迷的内容输入到这个输出中: KTs,QJs,ATo,
我是一个c ++的开始者。
答案 0 :(得分:0)
因为每只手占用4个字符(包括最后一个逗号),你可能只是将你的停靠点绕到最接近的4的倍数:
int stoppos = (169 * 7) / 100;
stoppos = stoppos - stoppos % 4; // round down to nearest multiple of 4
stoppos = (4 - stoppos % 4) + stoppos; // round up to nearest multiple of 4
这将输出 KT,QJ,或 KT,QJ,ATo,,具体取决于您选择向上还是向下舍入。如果您不想保留最后一个逗号,则可以执行额外的- 1
:
stoppos = stoppos - stoppos % 4 - 1;
有关如何舍入到最接近的4的倍数的更多想法,您可以查看this question
答案 1 :(得分:0)
使用此回答https://stackoverflow.com/a/3407254/2425366
中的功能int roundUp(int numToRound, int multiple) {
if(multiple == 0) return numToRound;
int remainder = numToRound % multiple;
if (remainder == 0) return numToRound;
return numToRound + multiple - remainder;
}
为stoppos = roundUp(stoppos, 4)
;
答案 2 :(得分:0)
这是一个演示程序,展示了如何完成它。
#include <iostream>
#include <string>
struct classInstance {};
int main()
{
std::string hand = "KTs,QJs,ATo,QTs,JTs,A9s,A9o,KQo,A8s,A8o,A7s,A7o,A6s,A6o,A5s,A5o,A4s,"
"99,A4o,A3s,A2s,KJo,J9s,T9s,Q9s,QJo,KTo,Q9o,88,77,66,QTo,A3o,A2o,JTo";
std::string::size_type start_pos;
std::string::size_type char_num;
start_pos = 0;
char_num = 7 * hand.size() / 100;
if ( start_pos + char_num < hand.size() )
{
char_num = hand.find( ',', start_pos + char_num );
if ( char_num != std::string::npos ) char_num -= start_pos - 1;
}
std::string s = hand.substr( start_pos, char_num );
std::cout << s << std::endl;
}
程序输出
KTs,QJs,ATo,
考虑成员函数substr
的第二个参数指定要提取的字符数。