如何在Java中将String数组转换为char数组

时间:2013-10-25 16:04:27

标签: java arrays string

我们得到一个字符串数组,我们需要的是一个char [],即所有字符串中所有字符的数组 例如:

输入:[我,爱你]

输出:[i,l,o,v,e,y,o,u]

首先我制作了一个数组数组。

然后我找到了所需char []数组的长度。

到目前为止,我已尝试过以下内容:

char[][] a1 = new char[str.length][];

for(int i =0;i<str.length;i++){
    a1[i]=str[i].toCharArray();
}

int total=0;
for(int i =0;i<str.length;i++){
    total = total + a1[i].length;
}

char[] allchar = new char[total];

for(int i=0;i<str.length;i++){
    //NOW HERE I WANT TO MERGE ALL THE char[] ARRAYS TOGETHER.
//HOW SHOULD I DO THIS?
}

6 个答案:

答案 0 :(得分:4)

String[] sArray = {"i", "love", "you"};
    String s = "";
    for (String n:sArray)
        s+= n;
    char[] c = s.toCharArray();

答案 1 :(得分:2)

你可以这样做

char[] allchar = new char[total]; // Your code till here is proper

// Copying the contents of the 2d array to a new 1d array
int counter = 0; // Counter as the index of your allChar array
for (int i = 0; i < a1.length; i++) { 
    for (int j = 0; j < a1[i].length; j++) { // nested for loop - typical 2d array format
        allchar[counter++] = a1[i][j]; // copying it to the new array
    }
}

答案 2 :(得分:1)

您可以执行以下方法之类的操作..

    public void converter(String[] stringArray) {


    char[] charsInArray = new char[500];    //set size of char array    
    int counterChars = 0;

    for (int i = 0; i < stringArray.length; i++) { 

        int counterLetters = 0; //declare counter for for amount of letters in each string in the array 

        for (int j = 0; j < stringArray[i].length(); j++) { 


            // below pretty self explanatory extracting individual strings and a
            charsInArray[counterChars] = stringArray[i].charAt(counterLetters);

            counterLetters++;
            counterChars++;
        }
    }


    }

答案 3 :(得分:1)

-ac 2

答案 4 :(得分:0)

public static void main(String[] args)
{
    String sentence="Gokul Krishna is class leader";
    String[] array=sentence.split("\\s");
    int counter;
    //String word = new String();
    for(String word:array)
    {
        counter=0;
        char[] wordArray=word.toCharArray();
        for(int i=0;i<wordArray.length;i++)
        {
            counter++;
        }
        System.out.println(word+ " :" +counter);
    }
}

答案 5 :(得分:0)

在Java 8中,我们可以使用流。

public char[] convert(String[] words) {
    return Arrays.stream(words)
            .collect(Collectors.joining())
            .toCharArray();
}

在这里,我们使用以下命令从数组创建流 Array.stream(T[] array),其中T是数组元素的类型。 比我们使用Collectors.joining()获得一个字符串。最后,我们使用String的toCharArray()方法获得一个char数组。