שתף באמצעות


Using String.Contains with case-insensitive arguments.

Question

Friday, December 8, 2006 1:02 AM

Is there any way to use

Dim Str as String = "UPPERlower"
Str.Contains("UpperLower") and have it return true?

All replies (8)

Friday, December 8, 2006 1:13 AM ✅Answered

The following will return true

Option Compare Text
Public Class Form1
    Private Sub StartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Str As String = "UPPERlower"
**        Dim b As Boolean = InStr(Str, "UpperLower")
**    End Sub
End Class


Friday, December 8, 2006 2:11 AM

That is exactly what I needed. Thank you very much.


Tuesday, May 1, 2007 12:49 PM

What about in C#, besides uppercasing or lowercasing both the target and the source?


Tuesday, February 19, 2008 7:57 PM | 3 votes

Code Snippet

string target = "mello yello";

string find = "Lo";

if (0 <= target.IndexOf(find, StringComparison.InvariantCultureIgnoreCase)) {

  // found

}

else {

  // not found

}


Monday, May 31, 2010 12:06 PM | 2 votes

The method I always use is the following (c#):

  Str.ToUpperInvariant().Contains("UpperLower".ToUpperInvariant());


Saturday, October 27, 2012 12:12 AM

This is expensive -- it constructs two UPPER CASE strings just to do a comparison. Caseless comparison is the preferred solution.


Thursday, March 7, 2013 8:19 AM

var _reps  = new List<string>();

(_reps.ConvertAll<string>(newConverter<string,string>(delegate(string str){str = str.ToLower(); return str;})).Contains("invisible"))
 

Thursday, October 3, 2013 7:54 PM

Use the IndexOf function instead.

e.g.:

if (searchString.IndexOf(searchValue, StringComparison.OrdinalIgnoreCase) >= 0)
{
  // Do Something...
}

Or you can add the following extension method to your project:

        /// <summary>
        /// Returns a value indicating whether the specified System.String object occurs within this string.
        /// </summary>
        /// <param name="source">A System.String object in which to locate the specified value.</param>
        /// <param name="value">A System.String object to be found within this string.</param>
        /// <param name="comparisonType">One of the enumeration values that specifies the rules for the search.</param>
        /// <returns>Returns true indicating the specified System.String object occurs within this string or false indicating the specified System.String object does not occur within this string.</returns>
        /// <exception cref="System.ArgumentNullException">System.ArgumentNullException</exception>
        public static bool Contains(this string source, string value, StringComparison comparisonType)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (value == null) throw new ArgumentNullException("value");

            return source.IndexOf(value, comparisonType) >= 0;
        }

- Mike Chatfield