章节目录
Java字符串
一. 简答题(共2题,100分)
1. (简答题)给定字符串String str1 = “hello”,字符串String str2 = “world”;1. 判断两个字符串的长度是否相等,输出结果;2.分别输出两个字符串字母‘o’的位置;3. 将两个字符串进行拼接并输出;4.将拼接的字符串“hello”后加上空格并输出。5.将拼接的整个字符串进行逆序,并输出。提交程序和运行截图,需注意编码规范。
public class Day1031 {
public static void tixtl1() {
String str1 = "hello";
String str2 = "world";
boolean isLength = str1.length() == str2.length();
System.out.println("两个字符串的长度是否相等:" + isLength);
int index1 = str1.indexOf('o');
int index2 = str2.indexOf('o');
System.out.println("字符串 str1 中字母 'o' 的位置:" + index1);
System.out.println("字符串 str2 中字母 'o' 的位置:" + index2);
String concatStr = str1.concat(str2);
System.out.println("拼接后的字符串:" + concatStr);
String string = str1 + " ";
String spacedStr = string.concat(str2);
System.out.println("加上空格后的字符串:" + spacedStr);
StringBuilder reversedStr = new StringBuilder(concatStr);
reversedStr.reverse();
System.out.println("逆序后的字符串:" + reversedStr.toString());
}
public static void main(String[] args) {
Day1031.tixtl1();
}
}
2. (简答题)给定字符串String str = “A man, a plan, a canal: Panama”。如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,字符串正着读和反着读都一样,则可以认为该字符串是一个 回文串 。判断给定的字符串是否为回文串。提交程序和运行截图,需注意编码规范。
public class tixtl2 {
public static void main(String[] args) {
String str = "A man, a plan, a canal: Panama";
String filteredStr = str.toLowerCase().replaceAll("[^a-z0-9]", "");
boolean isPalindrome = isPalindrome(filteredStr);
if (isPalindrome) {
System.out.println("给定的字符串是回文串");
} else {
System.out.println("给定的字符串不是回文串");
}
}
private static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}