加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 检查字符串是否以给定字符串开头

发布时间:2020-12-15 04:37:24 所属栏目:百科 来源:网络整理
导读:我是编程新手. 我需要确定给定的字符串是否以某些东西开头.例如,检查字符串是否以“hi”开头以返回true,但如果它为“high”则返回false. StartHi("hi there") - true;StartHi("hi") - true;StartHi("high five") - false. 我试过.Substring和.StartsWith,但

我是编程新手.
我需要确定给定的字符串是否以某些东西开头.例如,检查字符串是否以“hi”开头以返回true,但如果它为“high”则返回false.

StartHi("hi there") -> true;
StartHi("hi") -> true;
StartHi("high five") -> false.

我试过.Substring和.StartsWith,但我无法弄清楚如何让它们返回假“高五”.
我试过这样的:

public static bool StartHi(string str)
{
    bool firstHi;
    if(string.IsNullOrEmpty(str))
    {
        Console.WriteLine("The string is empty!");
    }
    else if(str.Substring(0,2) == "hi")
    {
        firstHi = true;
        Console.WriteLine("The string starts with "hi"");
    }
    else
    {
        firstHi = false;
        Console.WriteLine("The string doesn't start with "hi"");
    }
    Console.ReadLine();

    return firstHi;

}
使用.StartsWith,只需更改“else if”:

else if(str.StartsWith("hi"))
{
    firstHi = true;
    Console.WriteLine("The string starts with "hi"");
}

先感谢您!

最佳答案
使用Split编写如下所示的StartHi方法

    public static bool StartHi(string str)
    {
        bool firstHi = false;
        if (string.IsNullOrEmpty(str))
        {
            Console.WriteLine("The string is empty!");
            Console.ReadLine();
            return false;
        }

        var array = str.Split(new string[] {" "},StringSplitOptions.None);
        if (array[0].ToLower() == "hi")
        {
            firstHi = true;
            Console.WriteLine("The string starts with "hi"");
        }
        else
        {
            firstHi = false;
            Console.WriteLine("The string doesn't start with "hi"");
        }

        Console.ReadLine();

        return firstHi;
    }

注意:
如果你有其他字符串,如“你好!”或者“嗨?不要跟我打招呼”,然后你可以将斯普利特延伸到下面.

var array = str.Split(new string[] {" ","!","?"},StringSplitOptions.None);
if (array[0].ToLower() == "hi") //convert to lower and check

如果它变得更复杂并且朝向它,那么正则表达式可能是你最好的选择.我不能给它一个,因为我不是很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读