Search code examples
c#stringstartswith

"aaaa".StartsWith("aaa") returns false


If this is not a bug, can anyone then explain the reason behind this behavior? Indeed it seems that every odd number of letters will return false:

string test = "aaaaaaaaaaaaaaaaaaaa";
Console.WriteLine(test.StartsWith("aa"));
Console.WriteLine(test.StartsWith("aaa"));
Console.WriteLine(test.StartsWith("aaaa"));
Console.WriteLine(test.StartsWith("aaaaa"));
Console.WriteLine(test.StartsWith("aaaaaa"));
Console.WriteLine(test.StartsWith("aaaaaaa"));

yields following output when executed on a Danish system:

True
False
True
False
True
False

Solution

  • This is certainly due to your current culture. You may be in Danish in which aa is considered a letter. If you try changing the culture.. or the case, it shall work.

    I think I remember similar behaviour with hungarian cultures and letter associations

    Have a look to String StartsWith() issue with Danish text

    Example:

    using System;
    using System.Globalization;
    
    namespace Demo
    {
        public static class Program
        {
            public static void Main(string[] args)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("da-DK");
                System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
                string test = "aaaaaaaaaaaaaaaaaaaa";
                Console.WriteLine(test.StartsWith("aa"));
                Console.WriteLine(test.StartsWith("aaa"));
                Console.WriteLine(test.StartsWith("aaaa"));
                Console.WriteLine(test.StartsWith("aaaaa"));
                Console.WriteLine(test.StartsWith("aaaaaa"));
                Console.WriteLine(test.StartsWith("aaaaaaa"));
            }
        }
    }
    

    This prints what the OP claims.