简体   繁体   English

如何在Java中将字符串数组转换为字符数组?

[英]How to convert array of strings to array of characters in Java?

I'm hoping for some help trying to convert a String[] to a char[][].我希望在尝试将 String[] 转换为 char[][] 时得到一些帮助。 For example, given the array of strings:例如,给定字符串数组:

String[] example = ["aabba", "ababa", "aaaca"];

I want it to be:我希望它是:

char[][] example = {{'a','a','b','b','a'},
                  {'a','b','a','b','a'},
                  {'a','a','a','c','a'}};

I'm guessing using .getChar()/.charAt() would be useful but am not sure how to loop through the String array and separate the elements..how could I go about coding this transformation?我猜使用 .getChar()/.charAt() 会很有用,但我不确定如何循环遍历 String 数组并分隔元素..我该如何编码这个转换?

private static char[][] convertStringArrayToCharMultiDimension(String [] stringArray) {
    // Create the character multi-dimensional Array.
    // note that the 1st dimension is being initialized with the size of the string Array. We don't initialize the other dimension since we don't know the length of each String in the Array
    char[][] charMultiDimArray = new char[stringArray.length][];
    for (int i = 0; i  < stringArray.length; ++i) {
        charMultiDimArray[i] = stringArray[i].toCharArray();
    }

    // The length of the Multi-dimensional Array gives the length of the 1st Dimension.
    for (int i = 0; i  < charMultiDimArray.length; ++i) {
        System.out.println(charMultiDimArray[i]);
    }

    return charMultiDimArray;
}

Try this.尝试这个。

String[] example = {"aabba", "ababa", "aaaca"};
char[][] result = Arrays.stream(example)
    .map(s -> s.toCharArray())
    .toArray(char[][]::new);
System.out.println(Arrays.deepToString(result));

output输出

[a, a, b, b, a], [a, b, a, b, a], [a, a, a, c, a]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM