我正在尝试获取由特定字符(空格、逗号或点)分隔的句子,以检查它是否为回文。如果输入是“hello,potato.”,我将单独检查“hello”的对称性,然后单独检查 potato。
问题是,当我执行搜索定界符的循环的第一次迭代时,“hello”一词存储在子句中,但在第二次迭代中,应该存储为“马铃薯”将是“马铃薯”。而且我无法删除“。”输入字符串末尾的定界符。
for(int i=0;i<sentence.length();i++)
{
if(sentence[i]==' '||sentence[i]=='.'||sentence[i]==',')
{ //the couts is just to help me debug/trace
cout<<"i is now : "<<i<<endl;
if(i==delindex && i==sentence.length()-1)
{
subsentence=sentence.substr(temp+1,subsentence.length()-1);
}
else
{
subsentence=sentence.substr(delindex,i);
cout<<subsentence<<endl;
temp=delindex-1;
delindex=i+1;
}
}
}
解决此问题的最佳方法是什么?
最佳答案
god bless you man that strtok is what i have been looking for
实际上,您不需要 strtok
(并且出于各种安全原因可能应该避免使用它),因为 std::string
有一个很棒的方法,称为 find_first_of它的行为非常像 strtok
,因为它接受一堆字符并在遇到任何字符时返回索引。然而,要使健壮的分词器成为 find_first_of
和 find_first_not_of 的组合更适合这种情况。
因此您可以将 token 搜索简化为:
#include <iostream>
#include <string>
int main()
{
std::string sentence = "hello,potato tomato.";
std::string delims = " .,";
size_t beg, pos = 0;
while ((beg = sentence.find_first_not_of(delims, pos)) != std::string::npos)
{
pos = sentence.find_first_of(delims, beg + 1);
std::cout << sentence.substr(beg, pos - beg) << std::endl;
}
}
关于c++ - 子字符串和分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49119744/