user1513684
user1513684

Reputation: 105

searching of string according to start with each word in c#

I want to search a keyword by start with any word of any column.

For example displayedCustomers object contain Name which is Sameer Singh.

So when my search variable

searchOption="eer" //it should not search, 
searchOption="ingh" //it should not search,
searchOption="Sa" //it should search,
searchOption="Si" //it should search,
searchOption="ameer" //it should not search 

I am using this code previously for whole word.But don't know to split space of string and compare with starting element. Please help to do this in efficient way

Upvotes: 2

Views: 217

Answers (3)

Jeff
Jeff

Reputation: 12163

// Split the word by space
var split = str.Split(" ");
// Check if firstname or lastname starts with searchString
var found = split[0].StartsWith(searchString) || split[1].StartsWith(searchString);

If you dont know if the person has a middle name as well, and you wish to test on that as well:

var searchString = "Sam";
var split = customerName.Split(" ");
var found = false;
foreach(var str in split)
{
    found == found || str.StartsWith(searchString);
    if(found)
      break;
}

Wrapping this up in a method:

public bool NameStartsWith(string name,string searchStr)
{
    var split = name.Split(" ");
    foreach(var str in split)
    {
        if(str.StartsWith(searchString))
          return true;
    }
    return false;
}

Use it like this:

var matches = NameStartsWith("Sameer Singh","Sa"); // true
var matches = NameStartsWith("Sameer Singh","Si"); // true
var matches = NameStartsWith("Sameer Singh","S"); // true
var matches = NameStartsWith("Bobby Singer Bobberson","Sing"); // true
var matches = NameStartsWith("Sameer Singh","meer"); // false

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460138

You can use String.StartsWith

string name = "Sameer Singh";
string searchOption = "eer";
bool nameStartsWith = name.StartsWith(searchOption);

Console.Write("{0} {1} {2}"
                , name
                , nameStartsWith ? "starts with" : "starts not with"
                , searchOption);

Demo: http://ideone.com/mEh5Q1

You can do that for every word or every column in your record.

For example(assuming DataRow):

bool rowContains = row.ItemArray.Any(o => string.Format("{0}", o).StartsWith(searchOption));

assuming String[]:

bool arrContains = array.Any(str => str.StartsWith(searchOption));

assuming String:

bool nameContains = name.Split().Any(w => w.StartsWith(searchOption));

Upvotes: 2

Yannick Blondeau
Yannick Blondeau

Reputation: 9621

You should use String.StartsWith together with String.Split:

public bool IsMatching(string Name, string SearchOption)
{
    foreach (string s in Name.Split(' '))
    {
       if s.StartsWith(SearchOption)
          return true;
    }

    return false;
}

// use it like:
if IsMatching("Sameer Singh", "Sa")
{
    // ...

Upvotes: 2

Related Questions