“aaaa”.StartsWith(“aaa”) returns false

2019-04-03 16:48发布

问题:

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

回答1:

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.