精心整理了最新的面试资料和简历模板,有需要的可以自行获取
String
- 字符串是常量,创建之后不可改变。
- 字符串字面值存储在字符串池中,可以共享。.
- String s = “Hello” ;产生一个对象,字符串池中存储。
- String s = new String( “Hello”); //产生两个对象,堆、池各存储一个。
String常用方法
import java.util.Arrays;
public class Test06 {
public static void main(String[] args) {
String content = "hello world 你好 世界 hello world";
String name = " wo S hi, NI NN ";
//打印字符串长度
System.out.println(content.length());
//打印第三个字符
System.out.println(content.charAt(2));
//是否包含"he"
System.out.println(content.contains("he"));
//是否包含"sh"
System.out.println(content.contains("sh"));
//打印字符串对应的数组
System.out.println(Arrays.toString(content.toCharArray()));
//返回字符串首次出现的位置
System.out.println(content.indexOf("hello"));
//返回字符串最后一次出现的位置
System.out.println(content.lastIndexOf("hello"));
//去掉字符前后的空格
System.out.println(name.trim());
//把小写转换为大写
System.out.println(name.toUpperCase());
//把大写转换为小写
System.out.println(name.toLowerCase());
//判断以某字符串结尾
String file = "hello.html";
System.out.println(file.endsWith(".html"));
//判断以某字符串开头
System.out.println(file.startsWith("hello"));
//用新的字符串替换旧的字符串
System.out.println(content.replace("world","human"));
//对字符串进行拆分
String[] arr = name.split("[,]");
for (String string:arr
) {
System.out.println(string);
}
//不区分大小写比较
String s1 = "Student";
String s2 = "sTUDENT";
System.out.println(s1.equalsIgnoreCase(s2));
//compareTo()比较大小
String s3 = "abc";
String s4 = "xyz";
String s5 = "xyz";
System.out.println(s3.compareTo(s4));
System.out.println(s4.compareTo(s5));
}
}
可变字符串
- StringBuffer:可变长字符串,JDK1. 0提供,运行效率慢、线程安全。
- StringBuilder:可变长字符串,JDK5. 0提供,运行效率快、线程不安全。
常用方法:
public class Test07 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
//1.append()追加
sb.append("hello");
System.out.println(sb.toString());
sb.append("world");
System.out.println(sb.toString());
//2.insert()添加
sb.insert(0,"first");
System.out.println(sb.toString());
//3.replace()替换
sb.replace(0,5,"second");
System.out.println(sb.toString());
//4.delete()删除
sb.delete(0,5);
System.out.println(sb.toString());
}
}
检测String和StringBuffer耗时
public class Test01 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
// String str = "";
// for (int i = 0; i < 99999; i++) {
// str += i;
// }
// long end = System.currentTimeMillis();
// System.out.println("String耗时:" + (end - start));
StringBuffer sb = new StringBuffer();
for (int j = 0; j < 99999; j++) {
sb.append(j);
}
long end1 = System.currentTimeMillis();
System.out.println("StringBuffer耗时" + (end1 - start));
}
}