开发者

C++ search a string

I am having a really hard time with this problem...

Write a program that reads two strings (that do not contain blanks) called searchPattern and longSequence. The program will display in the screen the positions where searchPattern appears in longSequence. For example, when seachPattern is asd and longSewuence is asdfasdfasdfasdf (the positions are 0123456789012345) the program will display 0, 4, 8, 12. Another example, when seachPattern is jj and longSewuence is kjlkjjlkjjjlkjjjkl (the positions are 012开发者_JAVA技巧345678901234567) the program will display 4, 8, 9, 13, 14.

can anyone help?


Some hints:

  1. Read in the two strings. Look up "std::cin" for how to read and "std::string" for how to store the strings.

  2. Look at the std::string class's find() method to search for the substring in the long string.

Have a go and then post what you have done on here. You will find plenty of people happy to help you, but you have to make some effort yourself. :-)

As a starting point, maybe just write the part that reads in the strings. When that is working well, you can add features.

Good luck.


To start thinking about the solution of problems like this, the best way is to think how you would solve it using a pen and paper in as much detail as possible and then try to translate that to code.


I would use Test Driven Development and start out small and build up.

For example, forget about user I/O, and stick with hard-coded data:

#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;

int main(void) // For now, can be modified later.
{
  const char pattern[] = "asd";
  const char sequence[] = "asdfasdfasdfasdf";

  std::string::size_type position = 0;
  const std::string longSequence(sequence);
  position = longSequence.find(pattern, position);
  while (position != std::string::npos)
  {
    cout << "pattern found at position: " << position << endl;
    position = longSequence.find(pattern, position);
  }

  cout << "Paused. Press ENTER to continue." << endl;
  cin.ignore(100000, '\n');
  return 0;
}

You may want to convert the above into using a state machine rather than using std::string::find(). Again, this is just a foundation to build upon.


It's a recursive backtracking problem. Just like getting the mouse out of the maze. Define your base cases and your paths through the data. In the end all you need is a single function of maybe 15 - 20 lines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜