C# 之 字符串的截取拆分的几种方法

556 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

1, 使用SubString方法截取子串


通常使用情况:求已知字符串的哪一段...

static void String_Sub()
{
     string str_3 = "CSDN_Czhenya";
     
     //从第几位开始取,到结束, -- 输出是:_Czhenya
     string str_4 = str_3.Substring(4);
     
     //从第几位开始取,取几位, -- 输出是:_C     
     string str_5 = str_3.Substring(4,2);
     
     Console.WriteLine(str_4+" ... "+str_5);       
}

2, 使用split方法进行截取...


通常使用情况:使用特定的字符分割...

static void String_Split()
{
      string str_3 = "CSDN_Czhenya";
      string[] str_arr = str_3.Split('_');
      
      //输出结果:"str_arr[0]CSDN ...str_arr[0]Czhenya
      Console.WriteLine("str_arr[0]{0} ...str_arr[0]{1} " ,str_arr[0] , str_arr[1]);
}

特定的字符替换...

static void String_Split_1()
{
       string str_json = "CSDN_Czhenya";
       string[] str_arr = str_json.Split(new char[2] { '_', 'z' });

       //输出结果:CSDN ... C ... henya
       Console.WriteLine(str_arr[0]+" ... "+str_arr[1]+" ... "+str_arr[2]);
}

特定的字符串分割(下面例子:去一个Json字符串中特定的位置)...

static void String_Split_2()
{
       string str_json = "{\"name\":\"Czhenya\",\"url\":\"blog.csdn.net\",\"context\":\"C#\"}";
       string[] str_arr = str_json.Split(new string[2] { "url", "context" }, StringSplitOptions.RemoveEmptyEntries);

       //输出结果:{"name":"Czhenya"," ... ":"blog.csdn.net"," ... ":"C#"}
       Console.WriteLine(str_arr[0] + " ... " + str_arr[1] + " ... " + str_arr[2]);
}

3, 正则表达式...


相对比来讲效率会低一点

/// <summary>
/// 截取字符串...
/// </summary>
/// <param name="cut_Str">要截取的字符串</param>
/// <param name="start_Str">从哪个字符串开始截</param>
/// <param name="endstr">到那个结束</param>
/// <returns></returns>
static string CutString_ZZ(string cut_Str, string start_Str, string end_Str)
{
        Regex regex = new Regex("(?<=(" + start_Str + "))[.\\s\\S]*?(?=(" + end_Str + "))", RegexOptions.Multiline | RegexOptions.Singleline);
        return regex.Match(cut_Str).Value;
}

4, 使用Indexof的形式自己封装截取...


/// <summary>
/// IndexOf 截取字符串...
/// </summary>
/// <param name="cut_Str"></param>
/// <param name="start_Str"></param>
/// <param name="end_Str"></param>
/// <returns></returns>
public static string CutStr_Indexof(string cut_Str, string start_Str, string end_Str)
{
       string res = "";
       int start_Index, end_Index;//开始,结束索引...
       try
       {
            start_Index = cut_Str.IndexOf(start_Str);
            if (start_Index == -1)
                return res;
            string temp_str = cut_Str.Substring(start_Index + start_Str.Length);
                end_Index = temp_str.IndexOf(end_Str);
                if (end_Index == -1)
                    return res;
                res = temp_str.Remove(end_Index);
            }
            catch (Exception e)
            {
                Console.WriteLine("CutStr_Indexof Error:" + e.Message);
            }
            return res;
}