简体   繁体   English

Java二维字符数组

[英]Java two-dimensional array of chars

I need to write a java program that has an array-returning method that takes a two-dimensional array of chars as a parameter and returns a single-dimensional array of Strings. 我需要编写一个具有数组返回方法的Java程序,该方法将chars的二维数组作为参数并返回String的一维数组。 Here's what I have 这就是我所拥有的

import java.util.Scanner;
public class TwoDimArray {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of Rows?");
        int rows = s.nextInt();
        System.out.println("Enter the number of Colums?");
        int cols = s.nextInt();
        int [][] array = new int [rows] [cols];
    }

    public static char[ ] toCharArray(String token) {
        char[ ] NowString = new char[token.length( )];
        for (int i = 0; i < token.length( ); i++) {
            NowString[i] = token.charAt(i);
        }
        return NowString;
    }
}

You need an array of String, not of chars: 您需要一个String数组,而不是chars数组:

public static String[] ToStringArray(int[][] array) {
    String[] ret = new String[array.length]; 

    for (int i = 0; i < array.length; i++) {
       ret[i] = "";
       for(int j = 0; j < array[i].length; j++) {
          ret[i] += array[i][j];
       }

    }
    return ret;
}

The above answers are right; 以上答案是正确的; however you may want to use StringBuilder class to build the string rather than using "+=" to concatenate each char in the char array. 但是,您可能想使用StringBuilder类来构建字符串,而不是使用“ + =”来连接char数组中的每个char。

Using "+=" is inefficient because string are immutable type in java, so every time you append a character, it will have to create a new copy of the string with the one character appended to the end. 使用“ + =”效率不高,因为在Java中字符串是不可变的类型,因此,每次添加字符时,都必须创建一个新的字符串副本,并在其末尾附加一个字符。 This becomes very inefficient if you are appending a long array of char. 如果要附加一长串char,这将变得非常低效。

public String[] twoDArrayToCharArray(char[][] charArray) {
    String[] str = new String[charArray.length];
    for(int i = 0; i < charArray.length; i++){
        String temp = "";
        for(int j = 0; j < charArray[i].length; j++){
            temp += charArray[i][j];
        }
        str[i] = temp;
    }
    return str;
}

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

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