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

实现字符串的截取、拼接、替换和比较的Java函数有哪些?

发布时间:2023-06-29 05:51:43

在Java中,可以使用以下函数实现字符串的截取、拼接、替换和比较:

1. 字符串截取(Substring):

- substring(int beginIndex):从指定索引开始截取字符串的子串。

- substring(int beginIndex, int endIndex):从指定索引开始截取字符串的子串,截取到指定索引之前的字符。

2. 字符串拼接(Concatenation):

- concat(String str):将指定字符串连接到该字符串的末尾。

3. 字符串替换(Replace):

- replace(char oldChar, char newChar):用新字符替换字符串中所有出现的指定旧字符。

- replace(CharSequence target, CharSequence replacement):用新字符串替换字符串中所有出现的指定目标字符串。

4. 字符串比较(Comparison):

- equals(Object anObject):比较字符串与指定对象是否相等。

- equalsIgnoreCase(String anotherString):比较字符串与另一个字符串(忽略大小写)是否相等。

- compareTo(String anotherString):按字典顺序比较两个字符串。

- compareToIgnoreCase(String str):按字典顺序比较两个字符串(忽略大小写)。

下面是这些函数的示例使用:

String str = "Hello, World!";
String subStr = str.substring(7); // "World!"
String subStr2 = str.substring(7, 12); // "World"
String concatenated = str.concat(" Welcome"); // "Hello, World! Welcome"

String replaced = str.replace('l', 'L'); // "HeLLo, WorLd!"
String replaced2 = str.replace("llo", "llo"); // "Hella, World!"

boolean isEqual = str.equals("Hello, World!"); // true
boolean isIgnoreCaseEqual = str.equalsIgnoreCase("hello, world!"); // true
int compareResult = str.compareTo("Hello, World!"); // 0 (相等)
int compareIgnoreCaseResult = str.compareToIgnoreCase("hello, world!"); // 0 (相等)

这些函数都是String类的方法,在Java中可直接调用。输入一个字符串,通过使用这些函数,可以方便地实现截取、拼接、替换和比较字符串的需求。