1.字符串截取:
/**
* 功能:将java_520_字符串截取改为520字符串截取。
*/
public class TestFile {
public static void main(String[] args){
String name = "java_520_字符串截取";
int startNumber = name.indexOf("_");//4
String substring1 = name.substring(startNumber + 1, startNumber + 4);//包左不包右
int endNumber = name.lastIndexOf("_");//8
String substring2 = name.substring(endNumber+1);
String endName = substring1+substring2;
System.out.println(endName);
}
}
测试结果:
2.如果需要把多个字符串放在一起,用一个定界符分隔,可以使用静态join方法:
public static void main(String[] args) {
String str = String.join("/", "a", "b", "c", "d");
System.out.println(str);// a/b/c/d
}
3.检测两个字符串是否相等:
public class Test {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "Hello";
// 1.检测两个字符串是否相等
boolean a = str1.equals(str2);
System.out.println(a);//false
// 2.要想检测两个字符串是否相等,而不区分大小写
// 可以使用equalsIgnoreCase方法
boolean b = str1.equalsIgnoreCase(str2);
System.out.println(b);//true
}
}
4.空串和NULL串:
空串:长度为0的字符串
String str = "";//空串
System.out.println(str.length());// 0
System.out.println(str.equals(""));//true
NULL串:表示目前没有任何对象与该变量关联,如果在一个NULL值上调用方法,会出现错误。
String str = null;//NULL串
if (str==null){
System.out.println(true);
}
5.遍历字符串,打印每一个字符:
String str = "hello";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
6.compareTo()方法:按照字典顺序,如果字符串位于other之前,返回一个负数;如果字符串位于other之后,返回一个正数;如果两个字符串相等,返回0
public class Test {
public static void main(String[] args) {
String str1 = "aabb";
String str2 = "aacc";
String str3 = "aabb";
System.out.println(str1.compareTo(str2));// -1
//调换str1和str2的比较位置
System.out.println(str2.compareTo(str1));// 1
System.out.println(str1.compareTo(str3));// 0
}
}
7.startsWith()和endsWith()方法:以匹配的字符或字符串开头或结尾则返回true
String str1 = "aabb";
//以"a"开头
System.out.println(str1.startsWith("a"));// true
//以"bb"结尾
System.out.println(str1.endsWith("bb"));// true
8.其他常用方法:
public class Test {
public static void main(String[] args) {
String str1 = "aabbcd";
System.out.println(str1.indexOf("a"));// 0
System.out.println(str1.indexOf("bb"));// 2(前面两个a分开算)
//查找字符串中不存在的字符或字符串,返回-1
System.out.println(str1.indexOf("ee"));// -1
//从索引3开始查找
System.out.println(str1.indexOf("b", 3));// 3
//返回字符串的长度
System.out.println(str1.length());// 6
//替换
System.out.println(str1.replace("aa", "e"));// ebbcd
//截取字符串,返回一个新字符串
System.out.println(str1.substring(2));// bbcd
System.out.println(str1.substring(2, 4));// bb(包左不包右)
//转换成大写或小写
System.out.println(str1.toUpperCase());// AABBCD
System.out.println(str1.toLowerCase());// aabbcd
//删除字符串头部和尾部的空格
String str2 = " cc dd ss ";
System.out.println(str2.trim());// cc dd ss
}
}