在多维数组中设置字符串

时间:2017-11-09 13:06:33

标签: java arrays string multidimensional-array

我想在特定位置的多维数组中放置一个字符串。字符串应该从右到左书写。

public class PutStringInArray {

    public static void main(String[] args) {
            char[][] array1 = new char[10][10];
            String test = "Hello";
        char[2] = test;
    }
}

我意识到代码不能那样工作。在这个例子中,我希望字符串(在本例中为“hello”)以“array1 [2] [0]”开头,以“array1 [2] [4]”结尾。 它应填写如下:

array1 [2] [0] = h,
array1 [2] [1] = e,
array1 [2] [2] = l,
array1 [2] [3] = l,
array1 [2] [4] = o

这可能是一个非常简单的解决方案,但我无法理解。

3 个答案:

答案 0 :(得分:3)

您应该尝试将String转换为char数组。

char[][] array1 = new char[10][10];
String test = "Hello";
array1[2] = test.toCharArray();

修改

如果你想让字符串“Hello”开始到array1 [2] [2],你应该使用System.arraycopy

System.arraycopy(test.toCharArray(), 0, array1[2], 2, test.toCharArray().length)

请注意数组长度。

答案 1 :(得分:1)

更好的方法是不定义所需的列数。

char[][] arr = new char[10][];
arr[2] = "hello".toCharArray();
arr[7] = "world".toCharArray();
System.out.println(Arrays.toString(arr[2]));
System.out.println(Arrays.toString(arr[7]));

答案 2 :(得分:0)

您可以遍历val input: Vector[(Future[Int], Long)] = ??? val output: Future[Vector[(Int, Long)]] = Future.traverse(input) { case (f, v) => f.map(_ -> v) } 并将其放入索引String返回的数组中。就像下面的代码片段一样:

2

使用if语句,以便比数组大小更长的字符串被截断。