2012-07-16 212 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]進行比較,這會告訴你字符串是否相等。

另一種方法來做你想做的事情只是把數組放在集合並重復它。集合不會佔用相同內容的多個字符串!

參考文獻: