Find a partly match instead of perfect match (if-statement).

So i have a function that checks my vector for a search result (name_part) and if want my if-statement to return true if i found a partly match instead of exact match. Been looking for different ways to do this but came up empty.

For example if search for a part of a name for example "Oska" it will return false in the names "Oskar" "Oskari" "Oskarsson" but i want it to return true.

1
2
3
4
5
6
7
8
9
10
size_t find_in_names(vector<person> persons, string name_part)
{
	size_t antal = 0;
	for (int i = 0; i < persons.size(); i++) {
		if (persons[i].name == name_part)
			antal++;
	}

	return antal;
}
Last edited on
So how much of a match do you want?
Would just "O" satisfy your search criteria in your example?

You could write a bool function that compares two names however you wish and replace line 5.
 
  if (match_names(persons[i].name, name_part))


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct person
{   string  name;
};

//  Compare for the shorter of name and part
//  You may want to handle this differently if part is longer than name.
bool match_name (const string & name, const string & part)
{   size_t compare_len = min(name.size(), part.size());

    for (unsigned i=0; i<compare_len; i++)
        if (name[i] != part[i])
            return false;   //  No match
    return true;                    
}

size_t find_in_names(vector<person> persons, string name_part)
{   size_t antal = 0;

	for (unsigned i = 0; i < persons.size(); i++) 
	{   if (match_name (persons[i].name, name_part))
			antal++;
	}
	return antal;
}


Or if you're using C++11, you could use regular expression matching:
http://www.cplusplus.com/reference/regex/regex/



Last edited on
Topic archived. No new replies allowed.