常用类
1,String类
/* 统计一个String类对象字符串,大写字母,小写字母,非字母出现的次数 */ public class Test2 { public static void main(String[] args){ // //方法一 // String s = "abDJD, slkSDH,?.DK"; // int countL = 0; // int countD = 0; // int countF = 0; // for(int i = 0;i<s.length();i++){ // char c = s.charAt(i); // if(c>='a'&&c<='z'){ // countL++; // }else if(c>='A'&&c<='Z'){ // countD++; // }else{ // countF++; // } // } // System.out.printf("小写字母出现的次数%d\t",countL); // System.out.printf("大写字母出现的次数%d\t",countD); // System.out.printf("非字母出现的次数%d\t",countF); // System.out.println("-----------------------");
//方法二 String str1 = "a、b、c、d、e、f、g、h、i、j、k、l、m、n、o、p、q、r、s、t、u、v、w、x、y、z"; String str2 = "A、B、C、D、E、F、G、H、I、J、K、L、M、N、O、P、Q、R、S、T、U、V、W、X、Y、Z"; String s = "abDJD, slkSDH,?.DK"; int countL = 0; int countD = 0; int countF = 0; for(int i = 0;i<s.length();i++){ char c = s.charAt(i); if(str1.indexOf(c)!=-1){ countL++; }else if(str2.indexOf(c)!=-1){ countD++; }else{ countF++; } } System.out.printf("小写字母出现的次数%d\t",countL); System.out.printf("大写字母出现的次数%d\t",countD); System.out.printf("非字母出现的次数%d\t",countF); } }
/* 统一一个字符串在另一个字符串中出现的次数 */ public class TestString4 { public static void main(String[] args) { String str1 = "abcasdabcabc"; String str2 = "abc"; int index = -1; int cnt = 0; index = str1.indexOf(str2); while (-1 != index) { ++cnt; index = str1.indexOf(str2, index+str2.length()); } System.out.printf("%d\n", cnt); } }
StringBuffer
toString
public class TestToString { public static void main(String[] args){ point p = new point(3,4); System.out.println(p); } } class point{ int i,j; point(int i,int j){ this.i = i; this.j = j; } }
运行结果
public class TestToString { public static void main(String[] args){ point p = new point(3,4); System.out.println(p);//默认System.out.println(p.toString) } } class point{ int i,j; point(int i,int j){ this.i = i; this.j = j; } public String toString(){//重写父类的方法 return "["+i+","+j+"]"; } }