2012-09-25 58 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

不知何故,这看起来很复杂,我喜欢马克科恩使用的代码的想法,但不知何故它不适合我 –

相关问题