Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a substring within a string

In C++ I have a phonebook with many names, such as Sinatra, Frank, and I want the user to be able to input any length of string to scan the file for it. Once I have the user input a string of any desired length, how do I scan an entire string of "Sinatra, Frank" for just "Frank" or "Sinatra" or "atra" and see which name(s) it belongs to?

like image 749
Jonathan Haas Avatar asked Feb 09 '26 15:02

Jonathan Haas


2 Answers

You can use the std::string::find method:

string s = "Sinatra, Frank";
string::sizetype index = s.find("Frank");

This gets you the index of the match (which in this case is 9).

like image 157
Ken Wayne VanderLinde Avatar answered Feb 12 '26 14:02

Ken Wayne VanderLinde


A question: is your phonebook a flat file with each name on a new line (as in your example with "Sinatra, Frank" in a format like "Lastname, Firstname", etc.), or do you have some structure of this phonebook where each name-string is a node of an array, a linked list, etc?

Note that for strstr():

strstr(const char *s1, const char *s2)

locates the first occurrence of string s2 in s1, which may be sufficient for you.

For your input string, always be sure to check size limits in one way or another; if the user enters a string through some interface it should be explicitly handled to ensure it doesn't exceed your storage for it or contain malevolent characters or code.

Ken's solution produces the position of the substring in the original string (and so long as it's not null that mean's there's a 'hit') but doesn't tell you which entry of the phonebook is the hit; your code will need to track which entry/entries are hits so you can return a meaningful set of results.

like image 37
Daniel Alex Finkelstein Avatar answered Feb 12 '26 14:02

Daniel Alex Finkelstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!