0

我试图消除字符串数组中的额外元素,并编写了下面的代码。strcmp 函数和字符串数组似乎存在问题。strcmp 不接受这种方式的字符串数组元素。你能帮我解决这个问题吗?array3 是字符串数组。我正在用 C++ 进行编码,我想做的是在字符串数组中有多个“apple”或“banana”。但我只需要一个“苹果”或一个“香蕉”。

for(int l = 0; l<9999; l++)
{
    for(int m=l+1;m<10000;m++)
        if(!strcmp(array3[l],array3[m]))
        {
            array3[m]=array3[m+1];
        }
}
4

3 回答 3

1

首先,您可以使用operator==比较std::string类型的字符串:

std::string a = "asd";
std::string b = "asd";
if(a == b)
{
//do something
}

其次,如果 10000 是数组的大小,则代码中有错误:

array3[m]=array3[m+1];

在这一行中,您正在访问m+1st 元素,m最多可达 10000。这意味着您最终将尝试访问第 10001 个元素,并摆脱数组键。

最后,您的方法是错误的,这种方法不会让您删除所有重复的字符串。一个更好的(但不是最好的)方法是这样的(伪代码):

std::string array[];//initial array
std::string result[];//the array without duplicate elements
int resultSize = 0;//The number of unique elements.
bool isUnique = false;//A flag to indicate if the current element is unique.

for( int i = 0; i < array.size; i++ )
{ 
    isUnique = true;//we assume that the element is unique
    for( int j = 0; j < result.size; j++ ) 
    {
        if( array[i] == result[j] )
        {
            /*if the result array already contains such an element, it is, obviously, 
            not unique, and we have no interest in it.*/
            isUnique = false;
            break;
        }
    }
    //Now, if the isUnique flag is true, which means we didn't find a match in the result array,
    //we add the current element into the result array, and increase the count by one. 
    if( isUnique == true )
    {
        result[resultSize] = array[i];
        resultSize++;
    }
}
于 2012-07-16T08:04:08.653 回答
1

strcmp相等时返回 0,因此if (strcmp(s1,s2))...表示“如果字符串相等,则执行此操作...”。你是这个意思吗?

于 2012-07-16T07:03:14.123 回答
0

strcmp 仅适用于 Cstrings,因此如果您想使用它,我建议您将其更改为以下内容:strcmp(array3[l].c_str(),array3[m].c_str())这使字符串成为 C 字符串。

另一种选择是简单地将它们与相等运算符进行比较,array3[l]==array3[m]这将告诉您字符串是否相等。

做你想做的事情的另一种方法是将数组放在一个集合中并对其进行迭代。集合不包含多个相同内容的字符串!

参考:

于 2012-07-16T08:12:29.800 回答