String s1 = "hello";
// 返回字符串的长度:length方法
System.out.println("s1.length: " + s1.length());
/*
* 获取某索引处的字符:charAt(int index) 方法
* 注意:索引从0开始
*/
System.out.println("s1.charAt(0): " + s1.charAt(0));
// 判断字符串是否是空字符串:isEmpty()方法
System.out.println("s1.isEmpty(): " + s1.isEmpty());
/*
* 大小写转换
* 大写->小写:toLowerCase()方法
* 小写->大写:toUpperCase()方法
*/
System.out.println("s1.toUpperCase(): " + s1.toUpperCase());
// 取出字符串头尾的空格部分:trim()方法
String s2 = " exclude space ";
System.out.println("s2.trim(): " + s2.trim());
/*
* 比较字符串的内容是否相同:equals()方法
* 如果要忽略大小写使用equalsIgnoreCase()方法
*/
String s3 = "hello";
String s4 = "hello world";
System.out.println("s3.equals(s4): " + s3.equals(s4));
/*
* 连接字符串:
* 1. "+"
* 2. 使用concat()方法
* 注意:两种方法都是将字符串连接到末尾
*/
System.out.println("s1.concat(haha): " + s1.concat("haha"));
// 比较两个字符串的大小:compareTo()方法
System.out.println("s1.compareTo(hella): " + s1.compareTo("hella"));
/*
* 截取字符串:
* substring(int startIndex)方法:从startIndex开始截取到最后的一个字符串
* substring(int startIndex, int endIndex)方法:从从startIndex开始截取到endIndex(不包含)的一个字符串
*/
System.out.println("s1.substring(2): " + s1.substring(2));
System.out.println("s1.substring(1, 4): " + s1.substring(1, 4));
/*
* endIndex的值不可以比字符串的长度大,并且endIndex要大于startIndex
* 以下两种写法都会报错
* System.out.println("s1.substring(1, 6): " + s1.substring(1, 6));
* System.out.println("s1.substring(2, 1): " + s1.substring(2, 1));
*/
/*
* 判断字符串是否以某字符串开头或结尾
* 判断开头:startsWith(String suffix)方法
* 判断结尾:endsWith(String prefix)方法
* 如果传入第二个参数,表示从指定索引开始的子字符串是否以指定前缀开始或后缀结尾
* startsWith(String suffix, int offset) endsWith(String prefix, int offset)
*/
System.out.println("s1.startsWith(h): " + s1.startsWith("h"));
System.out.println("s1.endsWith(ll): " + s1.endsWith("ll"));
// 判断字符串是否包含某一子串:contains()方法
System.out.println("s1.contains(lo): " + s1.contains("lo"));
/*
* 替换字符串中某些内容
* 1. 替换某些字符,假设我想替换掉s1字符串中的l字符,换成r字符:s1.replace('l', 'r')
* 2. 替换某些字符串,假设我想替换掉s1中的lo字符子串,换成aa字符子串:s1.replace("ll", "aa")
*/
System.out.println("s1.replace('1', 'r'): " + s1.replace('l', 'r'));
System.out.println("s1.replcae(lo, aa): " + s1.replace("lo", "aa"));
// 切分字符串:split()方法 参数为正则表达式
String s5 = "a b c d e";
// 按照空格切分
System.out.println("s5.split( ): " + s5.split(" "));
Java String常用方法汇总(实际代码演示)
最新推荐文章于 2022-07-29 07:40:11 发布