The difference between C # IndexOf () and Contains ()

First, we first introduce the role of IndexOf () method and Contains () method, they are to determine whether the string contains the specified string

Same point:

IndexOf () method and Contains () are case sensitive

difference:

1. Case insensitive:

The IndexOf () method has a built-in parameter StringComparison.OrdinalIgnoreCase that can be set to be case insensitive

string str1="Abc";
string str2="abc";
str1.IndexOf(str2,StringComparison.OrdinalIgnoreCase);

The Contains () method can only convert all strings to uppercase or lowercase first to achieve case insensitivity

string str1="Abc";
string str2="abc";
str1.ToUpper().Contains(str2.ToUpper());

2. Matching efficiency:

In the case of case sensitivity, the Contains () method is more efficient than the IndexOf () method

In case-insensitive case, IndexOf () method is more efficient than Contains () method

3. Return value type:

The IndexOf () method contains the subscript that returns the first occurrence of the specified string. The subscript starts from 0, and -1 is returned if it does not.

Contains () method contains the specified string returns true, does not contain returns false.

Published 34 original articles · received 1 · views 1947

Guess you like

Origin blog.csdn.net/qq_38974638/article/details/103695192