以下是使用 C# 判断字符串首字母是否是 'ab' 开头的代码:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str = "abj";
        string str1 = "aj";
        string str2 = "bj";

        bool isAbStart = IsAbStart(str);
        Console.WriteLine("str starts with 'ab': " + isAbStart);

        bool isAbStart1 = IsAbStart(str1);
        Console.WriteLine("str1 starts with 'ab': " + isAbStart1);

        bool isAbStart2 = IsAbStart(str2);
        Console.WriteLine("str2 starts with 'ab': " + isAbStart2);
    }

    static bool IsAbStart(string str)
    {
        if (str.Length >= 2 && str.Substring(0, 2) == "ab")
        {
            return true;
        }
        return false;
    }
}

输出结果为:

str starts with 'ab': True
str1 starts with 'ab': False
str2 starts with 'ab': False

在上述代码中,我们定义了一个 IsAbStart 方法来判断字符串是否以 'ab' 开头。该方法首先检查字符串的长度是否大于等于 2,然后使用 Substring 方法取出字符串的前两个字符,并与 'ab' 进行比较。如果相等,则返回 true,表示字符串以 'ab' 开头;否则返回 false,表示字符串不以 'ab' 开头。

C# 判断字符串是否以 'ab' 开头

原文地址: https://www.cveoy.top/t/topic/pZmY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录