编写Java程序,实现以下功能:判断两个字符串是否相同、判断字符串的前缀、后缀是否和某个字符串相同、按字典序比较两个字符串的大小关系、检索字符串、将数字串转换成数字、获取字符串的字符数组、获取字符串指定编码的字节数组、用字符数组创建字符串、用字节数组创建字符串。
时间: 2023-12-02 22:03:34 浏览: 61
通用的Java工具类,主要包括基础工具类(时间、正则表达式、字符串、随机数等等),excel解析生成、word解析生成、文件操作、图片操作、敏感字、加解密等等
```java
import java.nio.charset.StandardCharsets;
public class StringDemo {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "world";
String str3 = "hello world";
String str4 = "hi";
String str5 = "hello world";
String str6 = "12345";
String str7 = "中文";
// 判断两个字符串是否相同
boolean isEqual = str1.equals(str2);
System.out.println("str1 equals str2: " + isEqual);
isEqual = str3.equals(str5);
System.out.println("str3 equals str5: " + isEqual);
// 判断字符串的前缀、后缀是否和某个字符串相同
boolean isStartsWith = str1.startsWith("he");
System.out.println("str1 starts with 'he': " + isStartsWith);
boolean isEndsWith = str2.endsWith("ld");
System.out.println("str2 ends with 'ld': " + isEndsWith);
// 按字典序比较两个字符串的大小关系
int result = str1.compareTo(str2);
System.out.println("str1 compareTo str2: " + result);
result = str1.compareTo(str4);
System.out.println("str1 compareTo str4: " + result);
// 检索字符串
int index = str3.indexOf("world");
System.out.println("Index of 'world' in str3: " + index);
index = str3.indexOf("java");
System.out.println("Index of 'java' in str3: " + index);
// 将数字串转换成数字
int num = Integer.parseInt(str6);
System.out.println("String to number: " + num);
// 获取字符串的字符数组
char[] charArray = str1.toCharArray();
System.out.println("String to char array: " + new String(charArray));
// 获取字符串指定编码的字节数组
byte[] byteArray = str7.getBytes(StandardCharsets.UTF_8);
System.out.println("String to byte array: " + new String(byteArray, StandardCharsets.UTF_8));
// 用字符数组创建字符串
String str8 = new String(new char[]{'h', 'e', 'l', 'l', 'o'});
System.out.println("Char array to string: " + str8);
// 用字节数组创建字符串
String str9 = new String(new byte[]{104, 101, 108, 108, 111}, StandardCharsets.UTF_8);
System.out.println("Byte array to string: " + str9);
}
}
```
阅读全文