Java字符串面试题
-
如何创建一个空字符串对象?
String str = new String();
-
如何判断两个字符串是否相等?
在Java中,可以使用
equals()
方法来判断两个字符串是否相等,例如:String str1 = "Hello"; String str2 = "World"; if (str1.equals(str2)) { System.out.println("Strings are equal"); } else { System.out.println("Strings are not equal"); }
-
如何将字符串转换为大写或小写?
可以使用
toUpperCase()
方法将字符串转换为大写,使用toLowerCase()
方法将字符串转换为小写,例如:String str = "Hello World"; String upperCase = str.toUpperCase(); String lowerCase = str.toLowerCase(); System.out.println("Uppercase: " + upperCase); System.out.println("Lowercase: " + lowerCase);
-
如何检查字符串是否以特定的前缀或后缀开头?
可以使用
startsWith()
方法检查字符串是否以特定的前缀开头,使用endsWith()
方法检查字符串是否以特定的后缀结尾,例如:String str = "Hello World"; if (str.startsWith("Hello")) { System.out.println("String starts with 'Hello'"); } if (str.endsWith("World")) { System.out.println("String ends with 'World'"); }
-
如何从字符串中提取子字符串?
可以使用
substring()
方法从字符串中提取子字符串,指定起始索引和结束索引(不包括结束索引),例如:String str = "Hello World"; String subStr = str.substring(6, 11); System.out.println("Substring: " + subStr);