一、倒序排序
public class Main {
public static void main(String[] args) {
String str = "Hello World!";
String reversedStr = reverseString(str);
System.out.println("原始字符串: " + str);
System.out.println("倒序字符串: " + reversedStr);
}
public static String reverseString(String input) {
StringBuilder sb = new StringBuilder(input);
return sb.reverse().toString();
}
}
在上述代码中,定义了一个名为 reverseString 的方法,它接受一个字符串参数 input 。通过创建一个 StringBuilder 对象来存储输入的字符串,然后调用 reverse 方法对字符串进行倒序,最后返回倒序后的字符串。在 main 方法中,定义了一个字符串 str ,并调用 reverseString 方法对其进行倒序,将结果存储在 reversedStr 变量中,并进行输出。
二、下标查找
以下是一个简单的 Java 代码示例,用于通过下标查找字符串中的字符:
public class SubIndexLookup {
public static void main(String[] args) {
String str = "Hello World!";
int index = 5;
char foundChar = lookUp(str, index);
System.out.println("在 " + str + " 中,下标为 " + index + " 的字符是:" + foundChar);
}
public static char lookUp(String str, int index) {
if (index < 0 || index >= str.length()) {
throw new IllegalArgumentException("无效的下标");
}
return str.charAt(index);
}
}
在上述代码中,定义了一个 lookUp 方法,用于根据给定的字符串和下标查找字符。它首先检查下标是否有效,如果无效则抛出异常。然后使用 charAt 方法根据下标获取对应的字符并返回。在 main 方法中,定义了一个字符串和一个下标,然后调用 lookUp 方法查找字符,并将结果输出。