如何将字符串转换为数组
时间: 2024-04-17 20:25:54 浏览: 14
这是一个Java应用程序,它可以实现以下功能:
1. 判断两个字符串是否相同
2. 判断字符串的前缀、后缀是否和某个字符串相同
3. 按字典顺序比较两个字符串的大小关系
4. 检索字符串
5. 创建字符串
6. 将数字型字符串转换为数字
7. 将字符串存放到数组中
8. 用字符数组创建字符串
下面是代码示例:
```java
import java.util.Arrays;
public class StringOperations {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "world";
String str3 = "hello world";
String str4 = "hello";
String str5 = "world";
String str6 = "java programming";
String str7 = "programming";
String str8 = "12345";
String str9 = "67890";
String[] strArray = {"apple", "banana", "cherry", "date", "elderberry"};
// 判断两个字符串是否相同
if (str1.equals(str4)) {
System.out.println("str1 and str4 are equal");
} else {
System.out.println("str1 and str4 are not equal");
}
// 判断字符串的前缀、后缀是否和某个字符串相同
if (str3.startsWith(str1)) {
System.out.println("str3 starts with str1");
} else {
System.out.println("str3 does not start with str1");
}
if (str3.endsWith(str2)) {
System.out.println("str3 ends with str2");
} else {
System.out.println("str3 does not end with str2");
}
// 按字典顺序比较两个字符串的大小关系
int result = str1.compareTo(str2);
if (result < ) {
System.out.println("str1 is less than str2");
} else if (result > ) {
System.out.println("str1 is greater than str2");
} else {
System.out.println("str1 is equal to str2");
}
// 检索字符串
int index = str6.indexOf(str7);
if (index != -1) {
System.out.println("str7 found at index " + index);
} else {
System.out.println("str7 not found");
}
// 创建字符串
String str10 = new String("hello");
System.out.println("str10: " + str10);
// 将数字型字符串转换为数字
int num1 = Integer.parseInt(str8);
int num2 = Integer.parseInt(str9);
System.out.println("num1 + num2 = " + (num1 + num2));
// 将字符串存放到数组中
String[] strArray2 = new String[5];
strArray2[] = "apple";
strArray2[1] = "banana";
strArray2[2] = "cherry";
strArray2[3] = "date";
strArray2[4] = "elderberry";
System.out.println(Arrays.toString(strArray2));
// 用字符数组创建字符串
char[] charArray = {'h', 'e', 'l', 'l', 'o'};
String str11 = new String(charArray);
System.out.println("str11: " + str11);
}
}
```