一、代码
package task_06_String;
/**
*用代码演示String类中的常用方法的用法。
*/
public class StringMethodTest
{
public static void isEmpty(String str) {
// boolean isEmpty(): 判断字符串是不是空串,如果是空的就返回true
if(str.isEmpty())
System.out.println(str+" 为空串");
else
System.out.println(str+" 不是空串");
}
public static void charAt(String str,int index) {
// char charAt(int index): 返回索引上的字符
System.out.println(str+" 索引为"+index+"的字符为:"+str.charAt(index));
}
public static void toLowerCase(String str) {
// String toLowerCase(): 字符串转成小写
System.out.println(str+" 转成小写为:"+str.toLowerCase());
}
public static void toUpperCase(String str) {
// String toUpperCase(): 字符串转成大写
System.out.println(str+" 转成大写写为:"+str.toUpperCase());
}
public static void repalceChar(String str,char oldChar, char newChar) {
// String repalce(char oldChar, char newChar): 将字符串中的老字符,替换为新字符
System.out.println("将字符串 "+str+" 中的字符 "+oldChar+" 替换成 "+newChar+" 后为:"+str.replace(oldChar, newChar));
}
public static void repalceString(String str,String old, String newstr) {
// String repalce(String old, String newstr): 将字符串中的老字符串,替换为新字符串
System.out.println("将字符串 "+str+" 中的字符串 "+old+" 替换成 "+newstr+" 后为:"+str.replace(old, newstr));
}
public static void trim(String str) {
// String trim(): 去掉字符串两端空格
System.out.println("\""+str+"\""+"去掉两端空格后为:"+"\""+str.trim()+"\"");
}
public static void main(String[] args)
{
String str1 = "";
String str2 = "Hello World";
isEmpty(str1);
isEmpty(str2);
charAt(str2,4);
toLowerCase(str2);
toUpperCase(str2);
repalceChar(str2,'l','x');
repalceString(str2,"ll","xx");
str2 = " h el lo ";
trim(str2);
}
}
二、运行结果