编写Java程序,实现以下功能:判断两个字符串是否相同、判断字符串的前缀、后缀是否和某个字符串相同、按字典序比较两个字符串的大小关系、检索字符串、将数字串转换成数字、获取字符串的字符数组、获取字符串指定编码的字节数组、用字符数组创建字符串、用字节数组创建字符串。
时间: 2023-06-20 13:03:33 浏览: 123
以下是实现上述功能的Java程序:
```java
public class StringDemo {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "Hello World";
String prefix = "hello";
String suffix = "world";
String cmpStr = "abc";
String searchStr = "o";
String numStr = "123";
String str3 = "abcdefghijklmnopqrstuvwxyz";
String charset = "UTF-8";
// 判断字符串是否相同
boolean isEqual = str1.equals(str2);
System.out.println("字符串是否相同:" + isEqual);
// 判断字符串前缀是否和某个字符串相同
boolean isPrefixEqual = str1.startsWith(prefix);
System.out.println("字符串前缀是否和某个字符串相同:" + isPrefixEqual);
// 判断字符串后缀是否和某个字符串相同
boolean isSuffixEqual = str1.endsWith(suffix);
System.out.println("字符串后缀是否和某个字符串相同:" + isSuffixEqual);
// 按字典序比较两个字符串的大小关系
int cmpResult = str1.compareTo(cmpStr);
System.out.println("按字典序比较两个字符串的大小关系:" + cmpResult);
// 检索字符串
int index = str1.indexOf(searchStr);
System.out.println("检索字符串:" + index);
// 将数字串转换成数字
int num = Integer.parseInt(numStr);
System.out.println("将数字串转换成数字:" + num);
// 获取字符串的字符数组
char[] charArray = str1.toCharArray();
System.out.println("获取字符串的字符数组:" + Arrays.toString(charArray));
try {
// 获取字符串指定编码的字节数组
byte[] byteUTF8 = str3.getBytes(charset);
System.out.println("获取字符串指定编码的字节数组:" + Arrays.toString(byteUTF8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 用字符数组创建字符串
char[] charArr = {'a', 'b', 'c'};
String str4 = new String(charArr);
System.out.println("用字符数组创建字符串:" + str4);
// 用字节数组创建字符串
byte[] byteArr = {97, 98, 99};
String str5 = new String(byteArr);
System.out.println("用字节数组创建字符串:" + str5);
}
}
```
输出结果为:
```
字符串是否相同:false
字符串前缀是否和某个字符串相同:true
字符串后缀是否和某个字符串相同:true
按字典序比较两个字符串的大小关系:7
检索字符串:4
将数字串转换成数字:123
获取字符串的字符数组:[h, e, l, l, o, , w, o, r, l, d]
获取字符串指定编码的字节数组:[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]
用字符数组创建字符串:abc
用字节数组创建字符串:abc
```
阅读全文