C# 取字符串中间文本 取字符串左边 取字符串右边

本文介绍了两种在C#中从字符串中截取特定部分的方法,对比了使用非空字符串和null作为参数的区别,详细解释了Between和Between2函数的实现逻辑,帮助读者理解如何高效地进行字符串操作。

  好像是第二种效率高一点,取str字符串中123左边的所有字符:第一种Between(str,"","123"),而第二种是Between(str,null,"123")。

public static string Between(string str, string strLeft, string strRight) //取文本中间
{
    if (str == null || str.Length == 0) return "";
    if (strLeft != "")
    {
        int indexLeft = str.IndexOf(strLeft);//左边字符串位置
        if (indexLeft < 0) return "";
        indexLeft = indexLeft + strLeft.Length;//左边字符串长度
        if (strRight != "")
        {
            int indexRight = str.IndexOf(strRight, indexLeft);//右边字符串位置
            if (indexRight < 0) return "";
            return str.Substring(indexLeft, indexRight - indexLeft);//indexRight - indexLeft是取中间字符串长度
                }
        else return str.Substring(indexLeft, str.Length - indexLeft);//取字符串右边
    }
    else//取字符串左边
    {
        int indexRight = str.IndexOf(strRight);
        if (indexRight <= 0) return "";
        else return str.Substring(0, indexRight);
    }
}

  

public static string Between2(string str, string strLeft, string strRight) //取文本中间
{
    if (str == null || str.Length == 0) return "";
    if (strLeft != null)
    {
        int indexLeft = str.IndexOf(strLeft);//左边字符串位置
        if (indexLeft < 0) return "";
        indexLeft = indexLeft + strLeft.Length;//左边字符串长度
        if (strRight != null)
        {
            int indexRight = str.IndexOf(strRight, indexLeft);//右边字符串位置
            if (indexRight < 0) return "";
            return str.Substring(indexLeft, indexRight - indexLeft);//indexRight - indexLeft是取中间字符串长度
                }
        else return str.Substring(indexLeft, str.Length - indexLeft);//取字符串右边
    }
    else//取字符串左边
    {
        if (strRight == null) return "";
        int indexRight = str.IndexOf(strRight);
        if (indexRight <= 0) return "";
        else return str.Substring(0, indexRight);
    }
}

转载于:https://www.cnblogs.com/mengms/p/9984305.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值