作者:忽然想起你_静_970 | 来源:互联网 | 2022-12-08 17:27
我正在闲暇时使用C++,我不能为我的生活似乎弄清楚如何计算字符串中特定字符之前的字符数.
例如:
Hello My Name \t is Bob!
我想让它计算之前的字符数(包括空格)\t
.
这是我的尝试:
std::string test = "Hello My Name \t is Bob!"
std::string::size_type pos = line.find("\t");
int numOfCharacters = 0;
while (pos == std::string::npos) {
numOfCharacters++;
pos = pos + 1;
}
我的理解.find()
是,如果npos
被检索,那意味着你没有找到你正在寻找的文本,所以我认为它会一直持续到我发现\t
所以它会从while循环开始.
1> Remy Lebeau..:
你的理解find()
是正确的,但你的使用npos
是错误的.
如果子被发现,你不进入循环,并numOfCharacters
保持为0.
如果找不到子字符串,则循环而不考虑字符串的内容,直到pos
最终增加到它变为npos
(-1)的点,并且numOfCharacters
最终会得到一个远不正确的值.
也许你在考虑更像这样的事情?
std::string test = "Hello My Name \t is Bob!"
std::string::size_type pos = line.find("\t");
std::string::size_type i = 0;
int numOfCharacters = 0;
while (i
但这将是多余的.字符串是0索引的,因此给定字符的索引也是它前面的字符数.如果你使用的话,根本不需要循环find()
:
std::string test = "Hello My Name \t is Bob!"
std::string::size_type pos = test.find("\t");
int numOfCharacters = static_cast(pos);
如果你要手动循环,那么find()
根本不要使用:
std::string test = "Hello My Name \t is Bob!"
int numOfCharacters = -1;
for(std::string::size_type pos = 0; pos (pos);
break;
}
}