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; break; } } if (IsEqual) { return(i); } } return(-1); }
//字符串比较,如果一样,返回0 //如果不一样,当前比较字符小于s中对应字符,返回-1 //如果当前字符大于s中对应字符,返回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); } } }
static void Main(string[] args) { StringDS str = new StringDS("abcdefg"); StringDS str1 = new StringDS("hijklmn"); StringDS str2 = new StringDS("abcdefg"); string s = "abc"; string s1 = "abc"; Console.WriteLine(s == s1); //对于值类型,如果对象的值相等,则相等运算符 (==) 返回 true,否则返回 false。 //对于string 以外的引用类型,==比较的是两个对象的地址,如果两个对象引用同一个对象,则 == 返回 true。 //对于 string 类型,== 比较字符串的值。 Console.WriteLine(str == str2); //==比较的是两个实例化对象的引用地址(指针),所以结果是false Console.WriteLine(str.Equals(str2)); //同上 Console.WriteLine("字符串str中索引为2的字符是" + str[2]); Console.WriteLine("字符串str1的长度是" + str1.GetLength()); Console.WriteLine(str.Compare(str1)); //Console.WriteLine(str.SubString(2, 2)==new StringDS("cd")); Console.WriteLine(s == s1); Console.WriteLine(str1.IndexOf(new StringDS("jk"))); Console.ReadKey(); }