常用方法
public class test1 {
public static void main(String[] args) {
String a = "Hello World";
String b = "Hello Java";
System.out.println(a.length()); // 返回字符串长度
System.out.println(a.charAt(1)); // 返回索引处的字符
System.out.println(a.isEmpty()); // 是否为空字符
System.out.println(a.toLowerCase()); // 将字符转为小写
System.out.println(a.toUpperCase()); // 将字符转为大写
System.out.println(a.trim()); // 获取字符串副本,并且删除空格
System.out.println(a.equals(b)); // 比较字符串内容是否相同
System.out.println(a.equalsIgnoreCase(b)); // 比较字符串内容是否相同,忽略大小写
System.out.println(a.concat(b)); // 将指定字符串连接到此字符串的结尾
System.out.println(a.compareTo(b)); // 比较两个字符串的大小
System.out.println(a.substring(0,2)); // 返回一个新字符串从0截取到2如果只有一个参数则从参数截取到最后
System.out.println(a.startsWith(b)); //判断字符串a是否以字符串b为开头
System.out.println(a.endsWith(b)); //判断字符串a是否以字符串b为结尾
System.out.println(a.contains(b)); //判断字符串a是否包含字符串b
System.out.println(a.indexOf(b)); //判断字符串a中字符串b是否存在并返回索引
System.out.println(a.replace("World","java")); //将字符串中World替换成java
System.out.println(a.replaceAll("H.*?d",",")); //使用正则替换
System.out.println(a.matches(".*?")); //判断字符串是否符合正则
System.out.println(a.split(" ")); //根据正则将字符串切片成数组
}
}
/*
11
e
false
hello world
HELLO WORLD
Hello World
false
false
Hello WorldHello Java
13
He
false
false
false
-1
Hello java
,
true
[Ljava.lang.String;@1b6d3586
Process finished with exit code 0
*/
String 转换成其他类型
public class test1 {
public static void main(String[] args) {
String a = "221";
System.out.println(Integer.parseInt(a));
}
}
// 类型.parsexxx()
String 转成字节数组
public class test1 {
public static void main(String[] args) {
String a = "221";
String b = "Hello Java";
byte []c = b.getBytes();
System.out.println(Arrays.toString(c));
}
}
//设置编码集为gbk
public class test1 {
public static void main(String[] args) throws UnsupportedEncodingException {
String a = "221";
String b = "Hello Java";
byte []c = b.getBytes("gbk");
System.out.println(Arrays.toString(c));
}
}
//字节转成String时设置编码集
String d = new String(c,"gbk");
StringBuffer
public class test1 {
public static void main(String[] args){
StringBuffer a= new StringBuffer("HelloWorld");
a.setCharAt(0,'2'); //将索引为1的字符改为2
a.append('1'); //在当前字符串后面增加1
a.delete(0,1); //删除索引0-1之间的字符
a.replace(0,1,"a"); //将索引0-1字符替换成a
a.insert(0,"ada"); //在指定位置增加字符
a.reverse(); //将当前字符逆转
System.out.println(a.charAt(1)); //查询索引1处的字符
}
}