[C #] Let String.contains ignore case (efficient comparison, avoid tolower () new string to occupy resources)

Source: Internet
Author: User
In C #, String.contains is case sensitive, so if you want to be in C # Using String.contains to determine whether a string contains a keyword keyword, it is less efficient to convert this string and keyword to lowercase and then call contains.

A good way to do this is to use the String.index () method, and then specify the lookup procedure by StringComparison.OrdinalIgnoreCase to ignore the case, as the following code example reads:

string title = "string";
BOOL contains = title. IndexOf ("string", StringComparison.OrdinalIgnoreCase) >= 0;

If you need to use it extensively in your project, consider encapsulating it as a method to add to the static tool class StringUtils.cs, or simply write an extension of the string class

public static bool Contains (this string source, string Tocheck, StringComparison comp) {return
    source. IndexOf (Tocheck, comp) >= 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.