2015-04-24 179 views
1
#include <iostream> 
#include <string> 
using namespace std; 

int main() { 
    string str_1 = "Gandalf"; 
    string str_2 = "dal"; 
    for (int i = 0; i <= str_1.length() - 2; i++) 
     for (int j = 0; j <= str_2.length(); j++) { 
      if (str_2[j] == str_1[i]) { 
       if (str_2[j + 1] == str_1[i + 1]) { 
        if (str_2[j + 2] == str_1[i + 2]) 
         cout << "true"; 
       } 
      } 
     } 
    return 0; 
} 

我可以做到这一点,但如果长度为str_2是4个字符,程序不起作用。 我希望那个程序可以为每个字符串的长度 工作,但是怎么样?检查C++中的另一个字符串中的字符串

+5

你想检查'str_1'是否包含'str_2'? ['return str_1.find(str_2)!= std :: string :: npos;'](http://en.cppreference.com/w/cpp/string/basic_string/find) – BoBTFish

+0

是的,str_1总是长于ste_2 –

+0

我不得不使用find() –

回答

0

你可以尝试这样的事:

for (int i = 0; i < str_1.length() - str_2.length(); i++) { 
    bool is_same = true; 
    for (int j = 0; j < str_2.length(); j++) { 
     if (str[i + j] != str_2[j]) { 
      is_same = false; 
      break; 
     } 
    } 
    if (is_same) { 
     std::cout << "true" << std:endl; 
    } 
} 

它的每一个字符遍历在str_1和检查开始在该点的字符序列是否相同str_2

2

下面的函数find基本上重现了std::string::find(没有起始位置参数)的行为。通过外串

  • 循环,然后在每一步:您需要
  • 遍历第二个字符串检查每个字符。
  • 如果其中任何一个失败,请回退到外部循环。
  • 如果我们完成整个内部循环,那么第二个字符串就在那里,并返回外部循环中的当前位置。
  • 如果我们在第一个字符串中空间不足,请跳过其余部分。

希望评论能够说明这一点。我还包括一个小的实用功能,将找到的位置变成真/假,以及一些测试。

#include <iomanip> 
#include <iostream> 
#include <string> 

std::string::size_type find(const std::string& s1, 
          const std::string& s2) 
    // return the position of s2 within s1, 
    // else npos if it is not present. 
{ 
    using size_type = std::string::size_type; 
    size_type curPos = 0; 
    size_type lim = s1.size(); 
    size_type innerLim = s2.size(); 

    for (; curPos<lim; ++curPos) { // loop through s1 
     if (lim < curPos+innerLim) { 
      break; // not enough space left 
     } 
     size_type innerPos = 0; 
     for(; innerPos < innerLim // loop through s2, while matching 
       && curPos + innerPos < lim 
       && s1[innerPos+curPos] == s2[innerPos]; 
       ++innerPos) ; // do nothing in the loop 
     if (innerPos == innerLim) { // matched the whole loop 
      return curPos; 
     } 
    } 
    return std::string::npos; // never matched 
} 

bool contains(const std::string& s1, 
       const std::string& s2) 
{ 
    return find(s1, s2)!=std::string::npos; 
} 


int main() 
{ 
    std::cout 
     << std::boolalpha 
     << contains("abc", "")  << '\n' // true 
     << contains("abc", "abc") << '\n' // true 
     << contains("abc", "bc") << '\n' // true 
     << contains("abc", "abcd") << '\n' // false 
     << contains("abc", "abd") << '\n' // false 
     << contains("abc", "xyz") << '\n';// false 
} 

这不仅仅是你真正需要的东西,而是它最接近地模拟了“真实”的答案(使用语言提供的设施)。此外,它使它不是一个伟大的家庭作业答案,但包含写作业答案的所有线索。

+1

此空间故意留空。 @BoBTFish最后非常重要。注意他做了什么。使用这个想法。明白它。写你自己的简单版本并提交。试图提交BoBTFish刚刚做的事情会让你在本学期剩下的时间里非常困难,因为很明显,你正在走上拥有大量已有知识的课程,否则你会被剽窃为首。窃取想法至少是编程的一半,但计算机科学还是有点不满。 – user4581301

相关问题