-2

Suppose,i have two strings.NameIs and Nam.Now i can check if one string is as same as the other using :

If (string1 == string2)

But it won't work here as the strings are not the same.But a portion of it is same.What i am trying to achieve is to check if my main string has any portion of the string given...I came across String.StartWith and EndWith methods but there,i need to specify what the string might start or end with but i cannot as the strings can be anything(that's why at the beginning,i said "Suppose").

So my first question is how to achieve this ? I don't want any step=to=step instruction but atleast a little bit of direction :)

However,if i get past that,there's still a drawback and it is the Case-Sensitive issue.I've come across this but i can't seem to figure the required implementation of this in my case because i need to overcome the first issue first.

How should i achieve these ?

Dr. Blake
  • 55
  • 1
  • 7

4 Answers4

3

For ordinal comparison you can use

str1.Contains(str2);

If you need your comparison to be case-insensitive you can do

str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) >= 0;

Note that you can hide the latter in an extension method, like

static bool ContainsIgnoreCase(this string @this, string other)
    => @this.IndexOf(other, StringComparison.OrdinalIgnoreCase) >= 0;
0

Use String.Contains

if (stringValue.ToLower().Contains(anotherString.ToLower())) {  
    // Do Work // 
}

Just remember to check that strings aren't null when doing contains comparing, or you will get an ArgumentNullException..

Woodrow
  • 2,740
  • 1
  • 14
  • 18
  • There are better ways to do case intensive checks than using `ToLower` or `ToUpper`. It works for most character sets, but some languages have letters that don't have 1-to-1 mappings from lower to upper case. – juharr Mar 27 '18 at 19:47
0

Easiest way is this:

a = a?.ToLowerInvariant();
b = b?.ToLowerInvariant();

if(a==null || b==null || a.Contains(b) || b.Contains(a))
{
    //do stuff
}

Why null propogates into true? Because if any variable is null it will definitly contains in other variable. The other two specs is just for non-null entries.

eocron
  • 6,885
  • 1
  • 21
  • 50
0

To check if substring is contained in main string, and to ignore case-sensitivity do this, its a boolean function that takes two string parameters:

public bool DoesStringExistInsideMainString(string mainString, string subString)
{
    return mainString.ToLower().Contains(subString.ToLower());

}
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40