C++字符串的迭代器问题

Iterator woes with C++ strings

本文关键字:问题 迭代器 字符串 C++      更新时间:2023-10-16

对于赋值,我们必须执行一个以各种方式操纵C++字符串的大型程序。它的大部分功能都在起作用,但这个特定的功能让我很困惑。我试图在第一个字母数字字符出现之前循环遍历一个字符串并删除所有非字母数字字符(制表符、空白换行符),然后在第一个非字母数字字符再次出现时结束字符串。例如,"bob-jon"将被保存为"bob"。在每个字符串都被认为是空的地方出现了问题。大多数同行都认为

*(point++) = *marker;

做不到,我应该在尝试其他事情之前改变这个。。。这是一种在将迭代器的值分配给另一个迭代器值的同时增加迭代器数量的方法吗?是这个问题还是别的什么?

void clean_entry( const string& j, string& k )
{
    string::iterator point = k.begin();
    bool checker = false;
    //cycle through the constant string and check for numbers and letters
    for(string::const_iterator marker = j.cbegin(); marker!=j.cend(); ++marker)
    {
        if( isalnum(*marker) == true )
        {
           *(point++) = *marker; //copy to the new k string if alphanum, and increment iterator
            cout << "I found a real letter!" << endl; //debugging
            checker = true;
        }
        else if( checker == true )
            break;
    }
    cout << "So far we have " << k << endl; //debugging
    if (checker == false )
        k = "(empty word)";
    cout << "The new string is " << k << " apparently." << endl; //debugging
}
  1. isalnum不返回bool。返回int。保证是,如果字符是字母数字,则返回非零,否则返回零。这意味着您无法将返回值与true进行比较,因为在进行比较之前,该比较会导致true转换为int,从而生成1。。if(isalnum(*marker))既是惯用语,也是实际有效的

    类似地,if( checker == true )是膨胀的并且应该是if(checker),并且if (checker == false )应该是if(!checker)

  2. 您的接口是有问题的,因为调用者必须确保k的大小足够大,以容纳生成的字符串。最好清除k,然后使用push_back()或类似程序,而不是迭代器

假设k.size()足够大,那么*(point++) = *marker;没有什么问题。