一、如何判断两个String是否相等??使用”==“还是使用”equals()“?
String str1 = "abc"; String str2 = "abc"; String str3 = new String("abc"); System.out.println(str1 == str2); //true System.out.println(str1 == str3); //false System.out.println(str1.equals(str3)); //true
二、如何实现String与基本数据类型的装换
String str1 = "123"; String str2 = "12.3"; String str3 = "true"; int a = Integer.parseInt(str1); //123 double d = Double.parseDouble(str2); //12.3 boolean flag = Boolean.parseBoolean(str3); //true
String str1 = "123"; String str2 = "12.3"; String str3 = "true"; int a = Integer.valueOf(str1); //123 double d = Double.valueOf(str2); //12.3 boolean flag = Boolean.valueOf(str3); //true
public static Integer valueOf(String s)
int a = 123; double b = 13.05; boolean flag = true; String str1 = String.valueOf(a); //123 String str2 = String.valueOf(b); //13.05 String str3 = String.valueOf(flag); //true
String str1 = a +""; //a String str2 = flag + ""; //true
int a = 123; boolean flag = true; String str1 = Integer.toString(a); //123 String str2 = Boolean.toString(flag); //true
public static String valueOf(double d) { return Double.toString(d);//其余的转换都与之类似 }
三、如何分割字符串
String str = "aa-bb-cc-dd"; String[] res = str.split("-"); //aa bb cc dd
String str4 = "aa bb cc dd"; String[] res = str4.split("\\s"); //aa bb cc dd
String str4 = "aa|bb|cc|dd"; String[] res = str4.split("\\|"); //aa bb cc dd
四、取子串
String str = "abcdefg"; str = str.substring(2, 5); //cde
String str = "abcdefg"; str = str.substring(2, 5)+""; //cde
五、如何将字符串转换日期
String str = "2013-9-24"; SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy-MM-dd"); Date date = format.parse(str); System.out.println(date); //Tue Sep 24 00:00:00 CST 2013
六、String,StringBuilder,StringBuffer的区别
七、在switch语句中使用字符串
switch (str) { case "a": break; case "b": break; }
八、让字符串重复出现
String str = "1234 "; String repeated = StringUtils.repeat(str,3); //1234 1234 1234
public String repeat(String str,int repeatTimes){ int inputLen = str.length(); //获取字符串的长度 int outputLen = inputLen * repeatTimes; //输出字符串的长度 switch (inputLen) { //当长度只有1或2时,选择直接使用字符操作,增加效率 case 1: return repeat(str.charAt(0), repeatTimes); case 2: char ch0 = str.charAt(0); char ch1 = str.charAt(1); char[] output = new char[outputLen]; for(int i = repeatTimes * 2 -1;i >=0;){ output[i] = ch0; output[i+1] = ch1; i +=2; } return output.toString(); default: StringBuilder buf = new StringBuilder(); for(int i = 0;i <= repeatTimes - 1; i++){ buf.append(str); } return buf.toString(); } } public String repeat(char ch,int repeatTimes){ char[] buf = new char[repeatTimes]; for(int i = repeatTimes-1; i >= 0; i--){ //复制repeatTimes buf[i] = ch; } return buf.toString(); }
九、如何计算指定字符在字符串里出现的次数
int n = StringUtils.countMatches("aaaabbbb", "a"); System.out.println(n);