> 文章列表 > JAVA中String类常用的方法

JAVA中String类常用的方法

JAVA中String类常用的方法

一、认识String类

String类存在java.lang包中。String类被final修饰,被final修饰的类不能被继承。String类创建的对象不能修改。

二、String类对象的创建

// 推荐第一种方式创建
// 第一种方式,变量赋值
String str = "hello world!";
// 第二种方式,通过new关键字创建对象
String str1 = new String("hello world");

三、String类常用的方法

1、获取字符串的长度

String str = "hello";
int len = str.length(); // len = 5

2、获取字符串某一位置的字符

String str = "hello";
chat ch = str.charAt(0); //ch = 'h';
// 注意:java中字符串被双引号包含,字符被单引号包含

3、提取字串

substring方法有两个参数index1、index2,截取[index1,index2)的子串。如果只传入一个参数,截取index1到字符串末尾的子串

String str = "hello";
String str1 = str.substring(2); // str1 = "llo";
String str2 = str.substring(1, 3); // str2 = "el";

4、字符串比较

equals方法可以比较两个字符串是否相等。相等返回true,不相等返回false

String str = "abc";
String str1 = "Abc";
String str2 = "abc";
System.out.println(str.equals(str, str1)); // false;
System.out.println(str.equals(str, str2)); // true;

5、判断是否包含某个子串

contains方法可以校验字符串是否包含某个子串

String str = "员工已删除";
String str1 = "已删除";
String str2 = "已禁用";
System.out.println(str.contains(str1)); // true;
System.out.println(str.contains(str2)); // false;

6、字符串拼接

concat方法可以将参数中的字符串拼接到当前字符串后

String str = "hello";
String str1 = " world!";
String str2 = str.concat(str1) // str2= "hello world!"

7、查找某个字符或字符串位于当前字符串的位置

indexOf方法可以获取某个字符或某个字符串在当前字符串中的位置,返回字符或子字符串在该字符串中的位置。若当前字符串中不存在参数中的字符或字符串,返回-1

String str = "hello";
int a = str.indexOf('l') // a = 2
int b = str.indexOf('el') // b = 1
int c = str.indexOf('ha') // c = -1
System.out.println(str =contains(str1)); // true;

8、字符串中字符的替换

replace方法中传入两个参数:oldChar, newChar。用newChar替换当前字符串中的所有oldChar

String str = "hello";
String str1 = str.replace('l', 'L'); // "heLLo"

9、字符串中大小写转换

toLowerCase方法将当前字符串中所有的字符转换为小写并返回。toUpperCase方法将当前字符串中所有的字符转换为大写并返回

String str = "Hello";
String str1 = str.toLowerCase(); // str1 = "hello"
String str2 = str.toUpperCase(); // str2 = "HELLO"

10、忽略字符串前后空格

trim方法返回忽略字符串前后空格的字符串

String str = " hello   ";
String str1 = str.trim(); // str1 = "hello"

11、判断字符串是否为空

isEmpty方法用来判断字符串是否为空,为空返回true,不为空返回false。

String str = " hello   ";
System.out.println(str.isEmpty();); // false;

12、将字符串转换为一个新的字符数组

toCharArray方法可以将当前字符串转换为一个新的字符数组返回。

String str = "hello";
char arr = str.ttoCharArray(); // arr = ['h', 'e', 'l', 'l', 'o']

13、判断字符串是否是以指定的子串开始

startsWith方法用来判断当前字符串是否是以某一个子串开始

String str = "hello";
System.out.println(str.startsWith("he")); // true;
System.out.println(str.startsWith("llo")); // false;

14、判断字符串是否是以指定的子串结尾

endsWith方法用来判断当前字符串是否是以某一个子串结尾

String str = "hello";
System.out.println(str.endsWith("he")); // false;
System.out.println(str.endsWith("llo")); // true;

15、根据匹配给定的正则表达式拆分字符串,返回拆分后的数组

split方法传入两个参数。String[] split(String regex,int limit),根据匹配给度不够的正则表达式拆分当前字符串。分割为limit份。返回拆分后的字符串数组。

String str = "hello";
System.out.println(str.split("")); // ;["h", "e", "l", "l", "o"]
System.out.println(str.split("", 2)); // ;["h", "ello"]