顺序串
public class SqString { char[] data; int length; SqString() { data = new char[30]; length = 0; } SqString(String s) { data = new char[30]; for(int i=0; i<s.length(); i++) { data[i] = s.charAt(i); } length = s.length(); } void strCopy(SqString s) { for(int i=0; i<s.length; i++) { data[i] = s.data[i]; } length = s.length; } boolean strEqual(SqString s) { if(length != s.length) return false; for(int i=0; i<length; i++) { if(data[i] != s.data[i]) { return false; } } return true; } int strLen() { return length; } void strConcat(SqString s) { for(int i=0; i<s.length; i++) { data[i+length] = s.data[i]; } length = length + s.length; } SqString subStr(int from, int to) { SqString s = new SqString(); if(from<0 || from >=length || from+1>to || to<=0 || to>length) { return s; } for(int i= from ; i<to; i++) { s.data[i-from] = data[i]; } s.length = to - from; return s; } void strInsert(int from, SqString s) { if(from <0 || from > length) { return; } for(int i=length-1 ; i>=from; i--) { data[i+s.length] = data[i]; } for(int i=0; i<s.length; i++) { data[i+from] = s.data[i]; } length += s.length; } SqString strDel(int from, int to) { SqString s = new SqString(); if(from<0 || from >=length || from+1>to || to<=0 || to>length) { return s; } for(int i=from ; i<to; i++) { s.data[i-from] = data[i]; } s.length = to - from; for(int i=to; i<length; i++) { data[i - to + from] = data[i]; } length -= (to-from); return s; } void strReplace(SqString s, int from, int to) { strDel(from, to); strInsert(from, s); } void display() { for(int i=0; i<length; i++) { System.out.print(data[i]); } System.out.println(); } int strCmp(SqString s) { int len; if(length < s.length) len = length; else len = s.length; for(int i=0; i<len; i++) { if(data[i] < s.data[i]) return -1; else if(data[i] > s.data[i]) return 1; } if(length == s.length) return 0; else if(length < s.length) { return -1; } else { return 1; } } public static void main(String[] args) { SqString s = new SqString("Hello"); s.display(); s.strCopy(new SqString(" World!")); s.display(); System.out.println(s.strEqual(new SqString(" World!"))); System.out.println(s.strLen()); s.strConcat(new SqString("Hello")); s.display(); SqString res = s.subStr(4, 12); res.display(); s.display(); s.strInsert(2, new SqString("qq")); s.display(); s.strInsert(14, new SqString("haha")); System.out.println(s.strLen()); s.display(); res = s.strDel(3, 8); s.display(); res = s.strDel(9, 13); s.display(); s.strReplace(new SqString("Tencent"), 2, 4); s.display(); System.out.println(s.strLen()); System.out.println(s.strCmp(new SqString(" WTencentHello"))); System.out.println(s.strCmp(new SqString(" WTencent"))); System.out.println(s.strCmp(new SqString(" WTencentHello4554"))); System.out.println(s.strCmp(new SqString(" Wt"))); } }
结果:
Hello World! true 7 World!Hello ld!Hello World!Hello Wqqorld!Hello 18 Wqqorld!Hellohaha Wq!Hellohaha Wq!Hello WTencentHello 14 0 1 -1 -1
版权声明:本文博主原创文章,博客,未经同意不得转载。