String str = new String(); System.out.println(str);
以上示例没有输出对象的哈希码,说明重写了toString()方法.
操作字符串的常用方法:
String s = "helloworld"; System.out.println(s.charAt(0)); //输出h,返回指定索引对应的字符 System.out.println(s.indexOf('l'));//输出2,返回指定字符出现的索引 System.out.println(s.indexOf('l',2));//输出3,返回从指定索引开始,指定字符第一次出现的索引 System.out.println(s.indexOf("hell"));//输出0,返回指定字符串出现的索引 System.out.println(s.indexOf("hell",1));//输出0,返回从指定索引开始,指定字符串第一次出现的索引 System.out.println(s.substring(1));//输出elloword,截取从指定索引开始的字符串 System.out.println(s.substring(1, 2));//输出e,截取两个索引之前的字符串,包左不包右
遍历字符串:
String str = "abcdef";
//方法1: for (int i = 0; i < str.length(); i++) { System.out.println(str.charAt(i)); } //方法2:char [] ch = str.toCharArray(); for (char c : ch) { System.out.println(c); }
统计字符串中大写字母,小写字母,数字的个数:
String testStr = "sasaFsR13"; int big = 0; int small = 0; int number = 0; for (int i = 0; i < testStr.length(); i++) { char ch = testStr.charAt(i); if (ch >= '0' && ch <= '9') { number++; } else if (ch >= 'a' && ch <= 'z') { small++; } else if (ch >= 'A' && ch <= 'Z') { big++; } } System.out.println("大写字母:" + big + "个"); System.out.println("小写字母:" + small + "个"); System.out.println("数字:" + number + "个"); }
字符串转换常用方法:
/* * 字符串的转换功能: * byte[] getBytes():通过字符串得到一个字节数组 * char[] toCharArray():通过字符串得到一个字符数组 * static String copyValueOf(char[] chs):把字符数组变成字符串 * static String valueOf(char[] chs):把字符数组变成字符串 * static String valueOf(int/boolean/long/obj/float/char i)基本类型:把任意类型转成字符串 * String toLowerCase():转成小写 * String toUpperCase():转成大写 * String concat(String str):字符串的连接 */ String str = "hello"; byte[] b = str.getBytes(); for (int i = 0; i < b.length; i++) { System.out.print(b[i]+",");//输出104,101,108,108,111, } char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { System.out.print(ch[i]+",");//输出h,e,l,l,o,hello } System.out.println(String.copyValueOf(ch));//输出hello System.out.println(String.valueOf(ch));//输出hello System.out.println(String.valueOf(11));//输出11(String), String a = "ABC"; System.out.println(a.toLowerCase());//输出abc System.out.println(str.toUpperCase());//输出Hello System.out.println(a.concat(str));//输出ABChello