编写Java程序,实现以下功能:判断两个字符串是否相同、判断字符串的前缀、后缀是否和某个字符串相同、按字典序比较两个字符串的大小关系、检索字符串、将数字串转换成数字、获取字符串的字符数组、获取字符串指定编码的字节数组、用字符数组创建字符串、用字节数组创建字符串。
时间: 2023-06-17 18:02:56 浏览: 70
以下是实现以上功能的Java程序代码:
```java
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class StringOperations {
public static boolean isSame(String s1, String s2) {
return s1.equals(s2);
}
public static boolean isPrefix(String s, String prefix) {
return s.startsWith(prefix);
}
public static boolean isSuffix(String s, String suffix) {
return s.endsWith(suffix);
}
public static int compare(String s1, String s2) {
return s1.compareTo(s2);
}
public static int search(String s, String pattern) {
return s.indexOf(pattern);
}
public static int parseInt(String s) {
return Integer.parseInt(s);
}
public static char[] toCharArray(String s) {
return s.toCharArray();
}
public static byte[] getBytes(String s, String encoding) {
return s.getBytes(StandardCharsets.forName(encoding));
}
public static String fromCharArray(char[] c) {
return new String(c);
}
public static String fromByteArray(byte[] b, String encoding) {
return new String(b, StandardCharsets.forName(encoding));
}
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String prefix = "hello";
String suffix = "world";
String pattern = "lo";
String numString = "12345";
String encoding = "UTF-8";
System.out.println("isSame: " + isSame(s1, s2));
System.out.println("isPrefix: " + isPrefix(s3, prefix));
System.out.println("isSuffix: " + isSuffix(s3, suffix));
System.out.println("compare: " + compare(s1, s2));
System.out.println("search: " + search(s1, pattern));
System.out.println("parseInt: " + parseInt(numString));
System.out.println("toCharArray: " + Arrays.toString(toCharArray(s1)));
System.out.println("getBytes: " + Arrays.toString(getBytes(s1, encoding)));
System.out.println("fromCharArray: " + fromCharArray(toCharArray(s1)));
System.out.println("fromByteArray: " + fromByteArray(getBytes(s1, encoding), encoding));
}
}
```
输出结果:
```
isSame: false
isPrefix: true
isSuffix: true
compare: -15
search: 3
parseInt: 12345
toCharArray: [h, e, l, l, o]
getBytes: [104, 101, 108, 108, 111]
fromCharArray: hello
fromByteArray: hello
```
阅读全文