Searching an array in C++

For my class, I am asked to create a program that accepts text from the user. After the user inputs the text, the program is to search through it to find a certain word or phrase. I know that I need to use an array, but I'm not sure how to. One of my classmates told me that he used a vector to do it, but I don't know how to do it with a vector either. I am not asking for anyone to write the program for me, I just need some steps in the right direction.
there is a function std::string::find that should get you going.

Use a number of solutions to input the text into a variable say s1. Set variable s2 to the string you want to search for then it should be simply

this is all assuming you aren't supposed to be using char arrays for your assignment. Really check the requirements before taking the easy route =D

1
2
3
4
5
6
std::size_t foundLocation = s1.find(s2);  // size_t variable to hold location of substring
if(foundLocation != std::string::npos) // std::string::npos represents no matches
{
   // the string WAS found at foundLocation
}
Last edited on
We can use anything, not just char arrays. I'm not sure how to use what you just gave me. Sorry, I'm really new and my teacher hardly explains anything that she asks us to do :(. All I have right now is an array that stores the text that the user inputs.
an array of what? strings, chars? should only need one string variable and a good getline statement to read in everything from one input line..

getline(std::cin, strVarName);

using strings requires #include <string> and using namespace std in the beginning of your program.

so...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string s1;
  string s2 = "find me";
  cout << "Enter text: ";
  getline(std::cin,s1);

  size_t foundLocation = s1.find(s2);

  if(foundLocation != std::string::npos)
  {
    cout << "Substring " << s2 << " was found at position " << foundLocation << '\n';
  }

  return(0);
}
Topic archived. No new replies allowed.