本人现在就是小菜鸟一个,真在学java的数据结构,这些博客随笔就是记录我这小菜鸟一步步成为老鸟的过程吧!
1 package com.str; 2 3 public interface IStatStr { 4 public int length(); //返回次字符串的度 5 public char charAt(int index); //返回指定索引出char的值 6 public int indexOf(char ch); //返回指定字符串在此字符串中第一次出现的索引,无则返回-1 7 public String repleceChar(char oldChar,char newChar); //返回一个新的字符串 8 public String subString(int beginIndex,int endIndex); //返回一个新的字符串,是截取得到的 9 10 }
1 package com.str; 2 3 public class Statstr implements IStatStr { 4 5 //字符串数组 6 private char [] chars; 7 //字符串长度 8 private int length; 9 public Statstr(char[] chars){ 10 this.chars = chars; 11 this.length = chars.length; 12 } 13 14 @Override 15 public int length() { 16 return length; 17 } 18 19 @Override 20 public char charAt(int index) { 21 return chars[index]; 22 } 23 24 @Override 25 public int indexOf(char ch) { 26 for(int i = 0;i<chars.length;i++){ 27 if(chars[i] == ch){ 28 return i; 29 } 30 } 31 return -1; 32 } 33 34 @Override 35 public String repleceChar(char oldChar,char newChar) { 36 String newStr = ""; 37 for(int i = 0;i<chars.length;i++){ //遍历chars,判断若有oldchar->替换为newchar 38 if(chars[i] == oldChar){ 39 chars[i] = newChar; 40 } 41 newStr +=chars[i]; //得到String类型的newStr并且返回 42 } 43 return newStr; 44 } 45 46 @Override 47 public String subString(int beginIndex, int endIndex) { 48 String subStr = ""; 49 int subLength = endIndex - beginIndex; 50 if(subLength <0 || beginIndex<0 || endIndex>chars.length-1){ 51 return "出现参数错误"; 52 }else{ 53 char [] subChar = new char[subLength+1]; 54 for(int i = beginIndex,j = 0;i<=endIndex;i++,j++){ 55 subChar[j] = chars[i]; 56 subStr +=subChar[j]; 57 } 58 } 59 return subStr; 60 } 61 62 }
1 package com.str; 2 3 public class Test { 4 public static void main(String[] args) { 5 String myStr = "DavidZhang"; 6 char[] myChar = myStr.toCharArray(); 7 Statstr test = new Statstr(myChar); 8 System.out.println("查询索引处的字符:"+test.charAt(3)); 9 System.out.println("测试字符的长度:"+myChar.length); 10 System.out.println("字符i在字符数组中的位置:"+test.indexOf('i')); 11 System.out.println("替换的字符:"+test.repleceChar('a', 'v')); 12 System.out.println("替换的字符串"+test.subString(5, 9)); 13 } 14 15 }
结果:
注:这只是测试。