(C#)重寫分隔符分割字符串 - string.Split(char[] separator)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        public static string[] MyStringSplit(string input, char[] separator)
        {
            string[] output = null;
            if (input != null && separator != null)
            {
                int num = 1;
                for (int i = 0; i < input.Length; i++)
                {
                    for (int j = 0; j < separator.Length; j++)
                    {
                        if (input[i] == separator[j])
                        {
                            num++;
                            break;
                        }
                    }
                }
                output = new string[num];
                int index = 0;
                bool isSeparator = false;
                for (int i = 0; i < input.Length; i++)
                {
                    for (int j = 0; j < separator.Length; j++)
                    {
                        if (input[i] == separator[j])
                        {
                            index++;
                            isSeparator = true;
                            break;
                        }
                        else
                            isSeparator = false;
                    }
                    if (!isSeparator)
                        output[index] += input[i].ToString();
                }
            }
            return output;
        }
        static void Main(string[] args)
        {
            //string test = null;
            //string test = string.Empty;
            string test = ".as f.,ad_sf..";
            char[] separators = new char[] { '.', ',', '_', ' ' };
            string[] a;
            a = test.Split(separators);
            Console.WriteLine(a.Length);
            foreach (string item in a)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("-------------------------------");
            a = MyStringSplit(test, separators);
            Console.WriteLine(a.Length);
            foreach (string item in a)
            {
                Console.WriteLine(item);
            }
        }
    }
}


 

發佈了25 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章