c++ - 子字符串和分隔符

标签 c++ string substring delimiter

我正在尝试获取由特定字符(空格、逗号或点)分隔的句子,以检查它是否为回文。如果输入是“hello,p​​otato.”,我将单独检查“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_offind_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;
    }
}

https://ideone.com/rhMyvG

关于c++ - 子字符串和分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49119744/

相关文章:

java - 使用循环创建子字符串

regex - bash,在冒号前提取字符串

c++ - 对图执行边收缩

c++ - 如何在 C++ 上检测 Windows 是 32 位还是 64 位?

c++ - 在 vector 中访问类中的 vector

php - PHP 值怎么可能包含不等于空字符串或 null 的零长度字符串?

java - 计算字符串中唯一字母的数量

c - 附加到 C 中的字符串

c++ - 如何将现有代码/位图分配给 MFC

Java 子串迭代问题