C++,如何让此函数删除存储在数组中的字符串

C++, How do get this function to delete the string stored in the array?

本文关键字:存储 数组 字符串 删除 函数 C++      更新时间:2023-10-16

>我有一个删除函数,它应该通过用以前的字符串覆盖数组中的字符串来删除它。查看函数看到覆盖匹配并应删除。但是我在 Delete 中为循环编写的代码并没有删除 Overide 占用的数组中的第一个位置,并且输出保持不变。 此外,+ 之后的每个短语都被添加到数组中,因此在数组中占据了四个位置,抱歉我无法使该部分看起来更好,格式搞砸了它。

int AR::Look(const std::string & word)
{
    int result = -1;
    for(int i=0; i<counter; ++i)
    {
        if( con[i].find(word) != std::string::npos)
            result = i;
    }
    return result;
}
void AR::Delete(const string & word)
{
    int loc = Look(word);
    if (loc == -1)
    {
         cout<<"word not foundn";
    }
    else
    {
         for(int i=0; i<counter-1,i++;)
         {
             con[i]= con[i+1];
         }
    }
}    

AR their
    Ar(1);
        theirAr + "Overload the +" + " operator as a member function " + "with chaining to add a string " + "to an Arrary object.";
        cout<<theirAr<<endl<<endl;

        cout<<"testing Delete and Look.  <<endl;
        theirAr.Delete("XXXXXX");
        theirAr.Delete("Overload");
        cout<<"Output after Delete and Look calledn";
        cout<<theirArray<<endl<<endl;

您正在查找字符串,但仅在未出现时使用该值写入错误;如果您在pos N处找到该字符串,则无论如何都将删除第一个字符串:

void AR::Delete(const string & word)
{
    int loc = Look(word);
    if (loc == -1)
    {
        cout<<"word not foundn";
    }
    else
    {
        for(int i=0;i<counter-1,i++;)  <--- Why don't you use loc here???
        {
            con[i]= con[i+1];
        }
    }
}

此外,您的Look方法最好在第一场比赛后返回:

for ... {
 if( con[i].find(word) != std::string::npos)
     return i;
}
return -1;

不确定这是否是您的问题,但不应该这样吗?

void AR::Delete(const string & word)
{
    int loc = Look(word);
    if (loc == -1)
    {
         cout<<"word not foundn";
    }
    else
    {
        for(int i=loc;i<counter-1,i++;)  // changes in this line
        {
           con[i]= con[i+1];
        }
    }
}    

从找到字符串的位置开始,然后开始向后打乱它们。另外,什么缩短了数组?即删除最后一个元素。看起来也缺少了。

试试这个:

int AR::Look(const std::string & word)
{
    for (int i = 0; i < counter; ++i)
    {
        if (con[i].find(word) != std::string::npos)
            return i;
    }
    return -1;
}
void AR::Delete(const string & word)
{
    int loc = Look(word);
    if (loc == -1)
    {
         cout << "word not found" << endl;
    }
    else
    {
         for (int i = loc+1; i < counter; ++i)
         {
             con[i-1] = con[i];
         }
         --counter;
    }
}