2012-07-16 213 views
0

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

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]; 
     } 
} 
+0

你是什么意思字符串数组中的额外元素? array3是什么类型的?你也应该指出哪种语言。 – Rndm 2012-07-16 06:52:23

+0

字符串数组中的每个元素都有多个实例。我的意思是不止一个相同的字符串。我只需要其中一个 – bahadirtr 2012-07-16 06:53:44

+0

你能解释“每个元素的多于一个实例吗?如果数组有”AABCDD“,所以你想要”ABCD“?? – Swanand 2012-07-16 06:58:07

回答

1

strcmp返回0平等,所以if (strcmp(s1,s2))...的意思是“如果两个字符串相等,那么这样做......”。你是这个意思吗?

+0

是的,我的意思是 – bahadirtr 2012-07-16 07:04:01

+0

所以,你需要在这种情况下使用(如果(strcmp(s1,s2)== 0) – Swanand 2012-07-16 07:07:49

+0

对不起,输入错误在C/C++中的整数值0评估为布尔型'假',所以测试实际上意味着“如果不等于...”,所以我认为你需要否定你的条件。 – johngirvin 2012-07-16 07:08:33

0

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

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

其次,你必须在你的代码中的错误,提供10000是数组的大小:

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

在这一行中,您正在访问m+1 st元素,其中m的值最高为10000.这意味着您最终将尝试访问10001st元素并脱离阵列绑定。

最后,你的方法是错误的,这种方式不会让你删除所有重复的字符串。 一个更好的(但不是最好的)的方式来做到这一点是这样(伪):

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++; 
    } 
} 
0

STRCMP只有这样,如果你想使用它,我建议你把它改成下面的Cstrings工作:strcmp(array3[l].c_str(),array3[m].c_str())这使得字符串C字符串。

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

另一种方法来做你想做的事情只是把数组放在集合并重复它。集合不会占用相同内容的多个字符串!

参考文献: