我正在尝试将数组拆分为单独的数组。
我有一连串的话。我把这些单词分成了一个数组。现在我试图将单词数组拆分成各自独立的数组。
示例:
string = "This is a string";
words = [This, is, a, string]
我希望我的输出为:
[This], [is], [a], [string]
这是我到目前为止所拥有的:
String[] words = string.split(" ");
String wordsArray = Arrays.toString(words);
System.out.println(wordsArray.split(" ").toString());
这是我的输出:
[Ljava.lang.String;@63947c6b
答案 0 :(得分:2)
你的意思是这样的,使用Arrays.deepToString()
来打印嵌套数组吗?
String string = "This is a string";
System.out.println(string);
String[] words = string.split(" ");
System.out.println(Arrays.toString(words));
String[][] wordsArray = new String[words.length][];
for (int i = 0; i < words.length; i++)
wordsArray[i] = new String[] { words[i] };
System.out.println(Arrays.deepToString(wordsArray));
输出
This is a string
[This, is, a, string]
[[This], [is], [a], [string]]
如果你只想构建你列出的字符串,这是一种更简单的方法:
String string = "This is a string";
StringJoiner joiner = new StringJoiner("], [", "[", "]");
for (String word : string.split(" "))
joiner.add(word);
System.out.println(joiner.toString());
输出
[This], [is], [a], [string]
或者在使用流的单个语句中相同:
System.out.println(Pattern.compile(" ")
.splitAsStream("This is a string")
.collect(Collectors.joining("], [", "[", "]")));
或者你可以欺骗并做到这一点:
String string = "This is a string";
System.out.println("[" + string.replaceAll(" ", "], [") + "]");
答案 1 :(得分:1)
以下是构建String[][]
的一种方式:
public static void main(String[] args) {
String str = "This is a string";
String[][] result = Arrays.stream(str.split(" "))
.map(word -> new String[] {word})
.toArray(String[][]::new);
// [[This], [is], [a], [string]]
String output = Arrays.deepToString(result);
output = output.substring(1, output.length()-1);
System.out.println(output);
}
正如您所注意到的,人们不会简单地将数组传递给println,因为它的默认toString方法不会显示其元素。因此,使用Arrays.toString或Arrays.deepToString方法打印数组元素。
答案 2 :(得分:0)
你可以这样做
words = "This is a string";
String[] wordsArray=words.split(" ");
Arrays.stream(wordsArray).map(s -> s="["+s+"]").forEach(System.out::println);
答案 3 :(得分:0)
String s = "THis is an example";
String[] sa = s.split("\\s+");
StringJoiner sj = new StringJoiner("], [");
for (String item : sa)
sj.add(item);
System.out.println("[" + sj + "]");
产地:
[THis], [is], [an], [example]
答案 4 :(得分:0)
如果你想简单地打印它,那么使用streams api很简单。这是一个例子:
String output = Arrays.stream("This is a string".split("\\s"))
.map(s -> "[" + s + "]")
.collect(Collectors.joining(", "));
答案 5 :(得分:0)
它可以简单地完成:
String string = "This is a string";
System.out.println(string);
String[] words = string.split(" ");
System.out.println(Arrays.toString(words));
String[][] wordsArray= new String[words.length][1];
for(int i=0;i<words.length;i++){
wordsArray[i][0]=words[i];
}
System.out.println(Arrays.deepToString(wordsArray));