java将字符串转化为数组
时间: 2023-10-11 14:07:05 浏览: 76
可以使用String类的`toCharArray()`方法将字符串转换为字符数组。
示例代码:
```java
String str = "hello";
char[] arr = str.toCharArray();
```
这样就将字符串"hello"转换为字符数组['h', 'e', 'l', 'l', 'o']。
相关问题
用Java编写字符串转化为数组
Sure, 这是一个Java的实现:
```java
public static int[] strToIntArray(String str) {
str = str.substring(1, str.length()-1);//去掉头尾的中括号
String[] strArr = str.split(",");//分离逗号分隔的字符串
int[] intArr = new int[strArr.length];
for(int i=0;i<strArr.length;i++){
intArr[i] = Integer.parseInt(strArr[i].trim());//转换为整型数组
}
return intArr;
}
```
你可以通过调用这个方法将一个字符串转换为整型数组。您还有其他问题吗?
java将字符串截取为数组
### Java 中将字符串分割成数组
在 Java 中,可以使用 `String` 类中的 `split(String regex)` 方法来实现字符串到数组的转换。此方法接收一个正则表达式作为参数,并按照该模式拆分输入字符串[^1]。
下面是一个具体的例子:
```java
public class Main {
public static void main(String[] args) {
String str = "apple,mango,orange";
// 使用逗号作为分隔符进行分割
String[] fruits = str.split(",");
// 输出结果
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
}
```
上述代码展示了如何通过指定分隔符(此处为逗号)将字符串 `"apple,mango,orange"` 转换成由各个水果名称组成的字符串数组并逐个打印出来。
当遇到更复杂的场景时,比如处理包含空白字符的情况,则可以在调用 `split()` 函数前先去除首尾多余的空格,或者直接利用更为灵活的正则表达式来进行匹配操作。
阅读全文
相关推荐













