首页 > 解决方案 > 如何检查数组字符串的最后一个字符是否以“A”结尾

问题描述

我制作了一个数组,用户在其中输入了几个名称,然后我希望程序将它们打印出来。如果字母以“a”结尾,我希望它改变颜色。这就是我在代码中的意思。

        Array.Sort(stodents);

        Console.WriteLine("----------");

        for (int i = 0; i < stodents.Length; i++)
        {
            if (What do I type here?)
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Blue;
            }
            Console.WriteLine(stodents[i]);
        }

所以是的,我希望它在字符串不以 A 结尾时使字符串变为蓝色,而当它以洋红色结尾时。

标签: c#

解决方案


您可以使用String.EndsWith方法。

if(stodents[i].EndsWith('a'))

该方法检查字符串是否以指定的字符/字符串结尾(取决于您使用的重载),如果找到匹配项则返回 true。

如果要使其不区分大小写检查,也可以将重载与StringComparison 枚举一起使用

例如,

if(stodents[i].EndsWith("a",StringComparison.CurrentCultureIgnoreCase))

推荐阅读