欢迎访问宙启技术站
智能推送

Java函数库中常用的字符串函数及使用方法

发布时间:2023-06-09 19:05:27

Java是一种广泛使用的编程语言,它的字符串函数库是很强大的,可以满足各种字符串处理需求。本文将介绍一些常用的Java字符串函数,包括字符串比较、字符串查找、字符串替换、字符串截取、字符串转换等。

一、字符串比较

1. equals()

这个方法用于比较两个字符串是否相等,如果相等则返回true,否则返回false。例如:

String str1 = "hello";
String str2 = "world";
boolean result1 = str1.equals(str2);  // false
boolean result2 = str1.equals("hello");  // true

2. equalsIgnoreCase()

与equals()方法类似,但是它忽略字符串的大小写。例如:

String str1 = "hello";
String str2 = "HELLO";
boolean result = str1.equalsIgnoreCase(str2);  // true

3. compareTo()

这个方法用于比较两个字符串的大小关系,如果调用这个方法的字符串比参数字符串小,则返回负数;如果相等,则返回0;如果调用这个方法的字符串比参数字符串大,则返回正数。例如:

String str1 = "hello";
String str2 = "world";
int result1 = str1.compareTo(str2);  // -15
int result2 = str2.compareTo(str1);  // 15
int result3 = str1.compareTo("hello");  // 0

二、字符串查找

1. indexOf()

这个方法用于在字符串中查找指定子串第一次出现的位置,如果找到了则返回该位置,否则返回-1。例如:

String str = "hello world";
int index = str.indexOf("world");  // 6

2. lastIndexOf()

与indexOf()方法类似,但是它从字符串的末尾开始查找子串,返回最后一次出现的位置。例如:

String str = "hello world";
int index = str.lastIndexOf("l");  // 9

三、字符串替换

1. replace()

这个方法用于将字符串中的某个字符或者子串全部替换成另一个字符或者子串。例如:

String str = "hello world";
String result = str.replace("hello", "hi");  // hi world

2. trim()

这个方法用于去除字符串首尾的空格。例如:

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

四、字符串截取

1. substring()

这个方法用于截取字符串中的一部分,并返回新的字符串。例如:

String str = "hello world";
String result = str.substring(2, 6);  // llo 

2. split()

这个方法用于将字符串按照指定分隔符分开,并返回一个字符串数组。例如:

String str = "1,2,3,4,5";
String[] result = str.split(",");  // {"1", "2", "3", "4", "5"}

五、字符串转换

1. toLowerCase()

这个方法用于将字符串中的大写字母改成小写字母。例如:

String str = "HELLO WORLD";
String result = str.toLowerCase();  // hello world

2. toUpperCase()

与toLowerCase()方法类似,但是它将字符串中的小写字母改成大写字母。例如:

String str = "hello world";
String result = str.toUpperCase();  // HELLO WORLD

以上就是Java函数库中常用的字符串函数及使用方法,这些函数可以帮助开发者快速完成字符串处理任务,提高开发效率。