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?
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).
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.
You can use strstr()
to locate one substring within a string.
If it's a std::string
, you can use the .find()
method of the "Sinatra,Frank" string
精彩评论