13.字符串类
namespace DSList
{
public class StringDS
{
//Field
private char[] data;
//Properties
public char this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
//Constructors
public StringDS(char[] arr)
{
data = new char[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
data[i] = arr[i];
}
}
public StringDS(StringDS str)
{
data = new char[str.GetLength()];
for (int i = 0; i < str.GetLength(); i++)
{
data[i] = str[i];
}
}
public StringDS(int len)
{
data = new char[len];
}
public StringDS()
: this(100)
{ }
//Base methods
public int GetLength()
{
return data.Length;
}
public int Compare(StringDS str)
{
int len = ((this.GetLength() < str.GetLength()) ? this.GetLength() : str.GetLength());
int i = 0;
for (i = 0; i < len; i++)
{
if (this[i] != str[i])
{
break;
}
}
if (i < len)
{
if (this[i] < str[i])
{
return -1;
}
else if (this[i] > str[i])
{
return 1;
}
}
else if (this.GetLength() == str.GetLength())
{
return 0;
}
else if (this.GetLength() < str.GetLength())
{
return -1;
}
return 1;
}
public StringDS SubString(int index, int len)
{
if (index < 0 || index > this.GetLength() - 1 || len < 0 || len > this.GetLength() - index)
{
Console.WriteLine("Position or Length is error!");
return null;
}
StringDS arr = new StringDS(len);
for (int i = 0; i < len; i++)
{
arr[i] = this[i + index - 1];
}
return arr;
}
public StringDS Concat(StringDS str)
{
StringDS arr = new StringDS(this.GetLength() + str.GetLength());
for (int i = 0; i < this.GetLength(); i++)
{
arr[i] = this[i];
}
for (int i = 0; i < str.GetLength(); i++)
{
arr[this.GetLength()+i] = str[i];
}
return arr;
}
public StringDS Insert(int index, StringDS str)
{
StringDS arr = new StringDS(this.GetLength() + str.GetLength());
if (index < 0 || index > this.GetLength() - 1)
{
Console.WriteLine("Position is error!");
return null;
}
for (int i = 0; i < index; i++)
{
arr[i] = this[i];
}
for (int i = 0; i < str.GetLength(); i++)
{
arr[index + i] = str[i];
}
for (int i = 0; i < this.GetLength() - index; i++)
{
arr[index + str.GetLength() + i] = this[index + i];
}
return arr;
}
public StringDS Remove(int index, int len)
{
if (index < 0 || index > this.GetLength() - 1 || len < 0 || len > this.GetLength() - index)
{
Console.WriteLine("Position or Length is error!");
return null;
}
StringDS arr = new StringDS(this.GetLength()-len);
for (int i = 0; i < index; i++)
{
arr[i] = this[i];
}
for (int i = 0; i < this.GetLength() - index - len; i++)
{
arr[index + i] = this[index + len + i];
}
return arr;
}
public int Index(StringDS str)
{
if (this.GetLength() < str.GetLength())
{
Console.WriteLine("There is not String str");
return -1;
}
for (int i = 0; i < this.GetLength(); i++)
{
if (this[i] == str[0])
{
int tmp = i;
int j = 0;
for (j = 0; j < str.GetLength(); j++)
{
if (this[i + j] != str[j])
{
break;
}
}
if (j == str.GetLength())
{
return tmp;
}
}
}
return -1;
}
public void Output()
{
foreach (char i in data)
{
Console.Write(i);
}
Console.WriteLine();
}
}
}