2012-09-25 56 views
1

讓說,我們必須找到一個字符串:C++使用字符串的一部分

string list[]= {"12.34.56.78","55.34.5","23.44.5"} 

我希望用戶輸入這也是一個字符串,字符串的一部分:例如串55 ,它會循環通過串和查找整個字符串和打印"55.34.5" 我在做什麼是:

str是一個字符串輸入和list是字符串的整個列表

for (int i=0; i<n; i++){ 
    for (int j=0; j<(list[i].length()); j++){ 
    for (int k=0; k<(str.length()); k++){ 
     if (list[i][j] == str[k]) 
     cout<<list[i]<<endl; 
     else 
     break; 

但是,這有一個問題,它不能正常工作。

更新:

,所以我已經更新了我的代碼:

for (int i=0; i<n; i++) 
    if (strncmp(list[i].c_str(), str.c_str(), str.length()) == 0)){ 
     cout<<list[i]<<endl; 
     } 

然而,這不輸出任何字符串。

+2

想在更高層次上的find成員函數...你有一個[string類](http://www.cplusplus.com/reference/string/string/string/ )看看這個類的成員函數,看看是否能提供你所需要的。 – amdn

+1

如果用戶輸入「34」會怎麼樣?你想讓前兩個字符串匹配(「12.34.56.78」和「55.34.5」)?換句話說,你在尋找用戶字符串是你的列表中的字符串的「substring」嗎? – amdn

+0

輸出兩種選擇,然後 –

回答

0

這是一個結合了上述兩個答案的答案。它使用std::string

for (int i=0; i < n; i++) { 
    if (list[i].find(str) != std::string::npos) { 
     std::cout << list[i] << std::endl; 
    } 
} 
2

這只是比較list [i]中的第一個字符和字符串中的第一個字符。如果相應的第一個字符匹配,它將打印整個第i個字符串,然後將k,即偏移量前進到str中,而不會更改與您比較的字符串的偏移量。我想你可以與內兩個循環分配,並使用一個固定長度字符串比較,即

for (int i=0; i < n; i++) { 
    if (strncmp(list[i].c_str(), str.c_str(), str.length()) == 0) { 
    // match 
    } 
} 
+0

whats strncmp? –

+0

http://www.cplusplus.com/reference/clibrary/cstring/strncmp/ –

+0

然而,你會如何匹配呢? –

2

對於任何功能狂熱者(see it work):

std::string findInList(const std::vector<std::string> &searchFrom, const std::string &lookFor) { 
    for (const std::string &s : searchFrom) { 
     if (s.find(lookFor) != std::string::npos) 
      return s; 
    } 

    return ""; 
} 

我使用的載體,而不是一個數組,因爲矢量更好,並且不需要額外的工作就可以獲取數組大小。如果沒有使用C++ 11,則正常的for循環可以很好地工作。

這也假設你想要返回第一個匹配。一個可能更好的選擇是返回一個字符串矢量,如果沒有找到,則爲空,這使得它明確表示沒有找到任何字符串,或者與其他字符一樣多。不要返回找到的字符串,只需將其添加到矢量並繼續,完成後返回矢量。

如果你想爲標準算法建模,你也可以讓它使用開始迭代器和結束迭代器,而不是實際的容器。這將允許您在包含數組的任何類型的容器上調用它,並在該容器中查看任何範圍。

基於這兩點考慮,你可以演變成這個(see it work):如果不使用C++ 11

template <typename Iterator> 
std::vector<std::string> findInList(Iterator start, const Iterator end, const std::string &lookFor) { 
    std::vector<std::string> ret; 

    for (; start != end; ++start) 
     if (start->find(lookFor) != std::string::npos) 
      ret.emplace_back(*start); 

    return ret; 
} 

再次,emplace_back可以push_back被交換出去。

+0

我實際上不想使用矢量,因爲這只是我的程序的一部分,所以它會改變它的其餘部分 –

+0

在這裏用向量替換數組不應該很難。這個想法就在那裏。 – CPlayer

+0

不知何故,這看起來很複雜,我喜歡馬克科恩使用的代碼的想法,但不知何故它不適合我 –

相關問題