C#中Split的使用

版权声明:欢迎转载,欢迎批评,共同学习,共同进步。如果有不正确的地方,希望帮我纠正! https://blog.csdn.net/qq_33461689/article/details/85108348

String.Split有六个重载方法

private string _testStr = "(AAA)123(BBB)";
    void Start()
    {
        string[] _temp;
        //public String[] Split(params char[] separator);
        //按参数字符拆分字符串,保留空字符
        _temp = _testStr.Split('(');
        LogSplitStr(_temp);//[],[AAA)123],[BBB)],
        _temp = _testStr.Split('(', ')');
        LogSplitStr(_temp);//[],[AAA],[123],[BBB],[],
        //public String[] Split(char[] separator, StringSplitOptions options);
        //按字符数组拆分字符串,不保留空字符
        _temp = _testStr.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
        LogSplitStr(_temp);//[AAA],[123],[BBB],
        //public String[] Split(String[] separator, StringSplitOptions options);
        //按字符串数组拆分字符串,不保留空字符
        _temp = _testStr.Split(new string[] { "AA", "BB" }, StringSplitOptions.RemoveEmptyEntries);
        LogSplitStr(_temp);//[(],[A)123(],[B)],
        //public String[] Split(char[] separator, int count);
        //按字符数组拆分字符串,返回字符串数组最大长度为Count
        _temp = _testStr.Split(new char[] { '(', ')' }, 5);
        LogSplitStr(_temp);//[],[AAA],[123],[BBB],[],
        //public String[] Split(char[] separator, int count, StringSplitOptions options);
        //按字符数组拆分字符串,返回字符串数组最大长度为Count 不保留空字符
        _temp = _testStr.Split(new char[] { '(', ')' },6, StringSplitOptions.RemoveEmptyEntries);
        LogSplitStr(_temp);//[AAA],[123],[BBB],
        //public String[] Split(String[] separator, int count, StringSplitOptions options);
        //按字符串数组拆分字符串,返回字符串数组最大长度为Count 不保留空字符
        _temp = _testStr.Split(new string[] { "AA", "BB" }, 6,StringSplitOptions.RemoveEmptyEntries);
        LogSplitStr(_temp);//[(],[A)123(],[B)],
    }
    private void LogSplitStr(string[]_temp)
    {
        string _tempStr = "";
        for (int i = 0; i < _temp.Length; i++)
        {
            _tempStr = _tempStr +"["+ _temp[i] + "],";
        }
        Debug.Log(_tempStr);
    }

正常的字符串分割就是传一个参数。

如果要分割的字符串里面有多个需要分割的字符时,可以传入多个分隔符。

特殊情况,如果头尾有分隔符,或者两个分隔符中间没有其他字符时,默认分割之后是保留空字符的,如果不需要空字符的话,可以传入参数StringSplitOptions.RemoveEmptyEntries移除掉空字符。

猜你喜欢

转载自blog.csdn.net/qq_33461689/article/details/85108348