package 串; public class String1 { //串的数组实现 即 顺序存储 char table[]; int number =0; public String1(){ //空构造函数 table = new char[80]; number = 0; } // public String1(){ // this(10); // } public String1(int n){ table = new char[n]; number = 0; } public String1(char c){ this(); table[0]=c; number=1; } public String1(char c[]){ this(c.length); //必须是函数的第一行语句才行 System.arraycopy(c, 0, table, 0, c.length); number=c.length; } public int length1(){ return number; } public void concat(char c){ this.table[number]=c; number++; } public void concat(String1 str){ for(int i=0;i<str.length1();i++){ // this.table[number]=str.charAt(i); // number++; this.concat(str.table[i]); } } public void concat(String str){ for(int i=0;i<str.length();i++){ this.concat(str.charAt(i)); } } public String1 substring(int i,int n){ //从i开始的,长度为n的串 String1 sub = new String1(); int j=0; if(i>=1&& i<=this.length1()){ i--; while(i+j<this.length1()&&j<n){ sub.table[j]=this.table[i+j]; j++; } sub.number = j; } return sub; } public int substring(String str){ //从i开始的,长度为n的串 int in = str.length(); if(in==0){ return -1; } int i=0; int j=0; while(i+j<this.length1()&&j<in){ j=0; if(this.table[i]==str.charAt(j)){ for(j=0;j<str.length()&&i+j<this.table.length&&this.table[i+j]==str.charAt(j);j++) j++; if(j==in){ return i; } } } return -1; } public int indexOf(String1 sub){ int i=0; boolean yes=false; while(sub.length1()>0&&i<number&&!yes){ int j=0; //************** while(j<sub.length1()&& this.table[j+i]==sub.table[j]){ j++; } if(j<=sub.length1()){ yes = true; }else { i++; } } if(yes){ return i+1; //返回子串的首字母位置 }else return 0; //为没有找到子串 } public void outputString(){ System.out.println(this.table+"开始:*********************"); for(int i=0;i<this.length1();i++){ System.out.print(this.table[i]); } System.out.println("\n"+this.table+"结束:*********************"); } public int indexOfchar(char c){ //获得c在串中的位置 for(int i=0;i<this.number;i++){ if(this.table[i]==c){ return i+1; } } return -1; } public char getIndexOf(int in){ //获得串中的第in个字符 if(in>=1&&in<=this.length1()){ return this.table[in-1]; }else return '-'; } public static void main(String args[]){ String1 str = new String1(); str.concat("zhang wang li zhao liu guang."); str.outputString(); String1 str2= new String1('u'); // System.out.println(str.indexOfchar('u')); String str21 = "guang"; } }