java-关键字与方法(四)
trim()方法:trim()方法用于去除字符串两端的空格或空白字符。示例:
String str = " Hello World ";
String trimmedStr = str.trim(); // trimmedStr 的值为 "Hello World"
在上面的例子中,trim() 方法去除了字符串 str 两端的空格,返回结果为 "Hello World"。
concat()方法:concat()方法用于将一个字符串连接到另一个字符串的末尾。示例:
String str1 = "Hello";
String str2 = "World";
String concatStr = str1.concat(str2); // concatStr 的值为 "HelloWorld"
在上面的例子中,concat() 方法将字符串 str2 连接到字符串 str1 的末尾,返回结果为 "HelloWorld"。
replace()方法:replace()方法用于将指定字符或子字符串替换为另一个字符或子字符串。示例:
String str = "Hello World";
String replacedStr = str.replace("o", "0"); // replacedStr 的值为 "Hell0 W0rld"
在上面的例子中,replace() 方法将字符串 str 中的字符 "o" 替换为 "0",返回结果为 "Hell0 W0rld"。
endsWith()方法:endsWith()方法用于检查字符串是否以指定的后缀结束。示例:
String str = "Hello World";
boolean endsWithorld = str.endsWith("orld"); // endsWithorld 的值为 true
在上面的例子中,endsWith() 方法检查字符串 str 是否以子字符串 "orld" 结束,返回结果为 true。
isEmpty()方法:isEmpty()方法用于检查字符串是否为空,即长度为0。示例:
String str = "";
boolean isEmptyStr = str.isEmpty(); // isEmptyStr 的值为 true
在上面的例子中,isEmpty() 方法检查字符串 str 是否为空,返回结果为 true。

浙公网安备 33010602011771号