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

我们给出了一个字符串数组,我们需要的是一个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? } 

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

你可以这样做

 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 } } 

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

  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++; } } } 
 String [] s = new String[]{"i", "love", "you"}; int length = 0; for (int i = 0; i < s.length; i++) { for (int j = 0; j < s[i].length(); j++) { length++; } } char [] c = new char[length]; int k = 0; for (int i = 0; i < s.length; i++) { for (int j = 0; j < s[i].length(); j++) { c[k] = s[i].charAt(j); k++; } } for (int j = 0; j < c.length; j++) { System.out.print("char is: " + c[j]); }