如何从文本文件中搜索字符串

时间:2014-04-29 09:35:58

标签: c++ arrays string file search

首先,这是我到目前为止的代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int arraysize = 35;
int i = 0;
string line;
string searchTerm;

int main()
{
    string words[arraysize];
    ifstream wordFile;
    wordFile.open ("wordFile.txt");
    if (wordFile.is_open())
    {
        while (! wordFile.eof())
        {
            getline (wordFile, line);
            words[i] = line;
            i++;
        }
        wordFile.close();
    }
    else
    {
        cout << "Unable to open file" << endl;
    }

    for (int x = 0; x < arraysize; x++)
    {
        cout << words[x] << " ";
    }

    cout << "\n\nEnter in a word you would like to search in the story above:" << endl;
    cin >> searchTerm;

    for (int y = 0; y < arraysize; y++)
    {
        if (words[y].compare(searchTerm) !=0)
        {
            cout << "No match found" << endl;
        }
    }
}

到目前为止我所拥有的是从文本文件读取然后打印这些单词的程序。我接下来要做的是让用户输入他们想要在文本文件中搜索的单词,如果有一个单词就像他们输入的单词那么打印那个单词如果没有打印出来“没有单词像在文本文件中那样“ 我只是无法弄清楚搜索,有关如何做到这一点的任何建议吗?

2 个答案:

答案 0 :(得分:0)

怎么样:

int found = -1;
for (int y = 0; y < arraysize; y++)
{
    if (words[y].compare(searchTerm) ==0)
    {
        found = y;
        break;
    }
}

if ( found != -1 )
   cout << "found!" << endl;
else
   cout << "No match found" << endl;

或更短:

if ( std::find(std::begin(words), std::end(words), searchTerm) == std::end(words) )
  cout << "not found";
else
  cout << "found";

答案 1 :(得分:0)

以下是如何在字符串

中搜索字符串的示例
// string::find
#include <iostream>       // std::cout
#include <string>         // std::string

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

  return 0;
}

这可以帮助您确切了解您需要做什么

注意参数pos如何用于搜索同一搜索字符串的第二个实例。的输出:

first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.