Search code examples
c#containslastindexof

String.Contains and String.LastIndexOf C# return different result?


I have this problem where String.Contains returns true and String.LastIndexOf returns -1. Could someone explain to me what happened? I am using .NET 4.5.

    static void Main(string[] args)
    {
        String wikiPageUrl = @"http://it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl";

        if (wikiPageUrl.Contains("wikipedia.org/wiki/"))
        {

            int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki/");

            Console.WriteLine(i);

        }
    }

Solution

  • Try using StringComparison.Ordinal

    This will compare the string by evaluating the numeric values of the corresponding chars in each string, this should work with the special chars you have in that example string

     string wikiPageUrl = @"http://it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl";
     int i = wikiPageUrl.LastIndexOf("http://it.wikipedia.org/wiki/", StringComparison.Ordinal);
    

    // returns 0;