由于串中的字符都是连续存储的,而在 C#中串具有恒定不变的特性,即字符串一经创建,就不能将其变长、变短或者改变其中任何的字符。所以,这里不讨论串的链式存储,也不用接口来表示串的操作。同样,把串看作是一个类,类名为 StringDS。取名为 StringDS 是为了和 C#自身的字符串类 String 相区别。类StringDS 只有一个字段,即存放串中字符序列的数组 data。由于串的运算有很多,类 StringDS 中只包含部分基本的运算。串类 StringDS中的方法和属性:
using System;
using System.Data.SqlTypes;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.ComTypes;
namespace 字符_串_
{
/// <summary>
/// 串
/// </summary>
public class StringDS
{
//用来储放字符串中的字符
public char[] data;
//构造方法
public StringDS(char[] array)
{
data = new char[array.Length];
for (int i = 0; i < data.Length; i++)
{
data[i] = array[i];
}
}
public StringDS(string str)
{
data = new char[str.Length];
for (int i = 0; i < data.Length; i++)
{
data[i] = str[i];
}
}
//索引器
public char this[int index]
{
get { return data[index]; }
}
//
public int GetLength()
{
return data.Length;
}
//比较俩字符串是否相同
///如果相同返回 0
///如果 A字符大于B字符 返回 1
///如果 A字符小于B字符 返回 -1
public int Compare(StringDS s)
{
int len = this.GetLength() < s.GetLength() ? this.GetLength() : s.GetLength();
int index = -1;//储存不相等的字符的索引位置
for (int i = 0; i < len; i++)
{
if (this[i] != s[i])
{
index = i;
break;
}
}
if (index != -1)
{
if (this[index] > s[index])
{
return 1;
}
else
{
return -1;
}
}
else
{
if (this.GetLength() == s.GetLength())
{
return 0;
}
else
{
if (this.GetLength() > s.GetLength())
{
return 1;
}
else
{
return -1;
}
}
}
}
//截取一段字符串
public StringDS SubString(int index, int length)
{
char[] newData = new char[length];
for (int i = index; i < index + length; i++)
{
newData[i - index] = data[i];
}
return new StringDS(newData);
}
//俩字符串连接
public static StringDS Concat(StringDS s1, StringDS s2)
{
char[] newData = new char[s1.GetLength() + s2.GetLength()];
for (int i = 0; i < s1.GetLength(); i++)
{
newData[i] = s1[i];
}
for (int i = s1.GetLength(); i < newData.Length; i++)
{
newData[i] = s2[i - s1.GetLength()];
}
return new StringDS(newData);
}
//查找指定串返回下标索引
public int IndexOf(StringDS s)
{
for (int i = 0; i < this.GetLength() - s.GetLength(); i++)
{
bool isEqual = true;//字符串是否相同
for (int j = i; j < i + s.GetLength(); j++)
{
if (this[j] != s[j - i])
{
isEqual = false;
}
}
if (isEqual)
{
return i;
}
else
{
continue;
}
}
return -1;
}
public string ToString()
{
return new string(data);
}
}
}