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

时间:2023-01-03 19:10:36

修改了以前的同名文章里的方法并且增加了另一个方法实现string.Split(char[] separator)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
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;
output[index] = string.Empty;
break;
}
else
isSeparator = false;
}
if (!isSeparator)
output[index] += input[i].ToString();
}
if (output[0] == null)
output[0] = string.Empty;
}
return output;
}

public static string[] MyStringSplitNew(string input, char[] separator)
{
if (input != null && separator != null)
{
ArrayList outputList = new ArrayList();
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++;
outputList.Add(string.Empty);
isSeparator = true;
break;
}
else
isSeparator = false;
}
if (!isSeparator)
{
if (outputList.Count == index + 1)
outputList[index] += input[i].ToString();
else
outputList.Add(input[i].ToString());
}

}
return outputList.Cast<string>().ToArray();
}
else
return null;
}
static void Main(string[] args)
{
//string test = null;
//string test = string.Empty;
string test = ".asf.,ad_sf..";
char[] separators = new char[] { '.', ',', '_', ' ' };
string[] a;
a = test.Split(separators);
PrintArray(a);
Console.WriteLine("-------------------------------");
a = MyStringSplit(test, separators);
PrintArray(a);
Console.WriteLine("-------------------------------");
a = MyStringSplitNew(test, separators);
PrintArray(a);

}

public static void PrintArray(string[] input)
{
if (input != null && input.Length != 0)
{
Console.WriteLine("length: " + input.Length);

foreach (string item in input)
{
if (item == null)
Console.WriteLine("\"null\"");
else if (item == string.Empty)
Console.WriteLine("\"empty\"");
else
Console.WriteLine(item);
}
}
}
}
}