java将数组平均分割成多个
时间: 2023-09-17 20:09:53 浏览: 55
您可以使用以下代码将一个数组平均分割成多个子数组:
```java
public static int[][] splitArray(int[] array, int parts) {
int[][] result = new int[parts][];
int length = array.length;
int chunkSize = length / parts;
int leftOver = length % parts;
int index = 0;
for (int i = 0; i < parts; i++) {
int chunkLength = chunkSize + (leftOver-- > 0 ? 1 : 0);
int[] chunk = new int[chunkLength];
System.arraycopy(array, index, chunk, 0, chunkLength);
result[i] = chunk;
index += chunkLength;
}
return result;
}
```
该方法接收一个整数数组和要分割成的子数组数量,然后返回一个二维整数数组,其中包含指定数量的子数组。每个子数组的大小相等或相差不超过 1。
相关问题
java将JSONarray数组平均分割成多个
您可以使用以下代码将一个 `JSONArray` 平均分割成多个子数组:
```java
public static JSONArray[] splitJsonArray(JSONArray jsonArray, int parts) {
JSONArray[] result = new JSONArray[parts];
int length = jsonArray.length();
int chunkSize = length / parts;
int leftOver = length % parts;
int index = 0;
for (int i = 0; i < parts; i++) {
int chunkLength = chunkSize + (leftOver-- > 0 ? 1 : 0);
JSONArray chunk = new JSONArray();
for (int j = 0; j < chunkLength; j++) {
chunk.put(jsonArray.get(index++));
}
result[i] = chunk;
}
return result;
}
```
该方法接收一个 `JSONArray` 和要分割成的子数组数量,然后返回一个 `JSONArray` 数组,其中包含指定数量的子数组。每个子数组的大小相等或相差不超过 1。请注意,该方法是基于 `org.json` 库编写的。如果您使用其他 JSON 库,需要根据库的 API 进行相应的更改。
java 分割多个空格
如果要分割多个连续的空格,可以使用正则表达式来实现。示例代码如下:
```java
String str = "Hello World";
String[] strArr = str.split("\\s+"); // 以多个空格分割字符串
```
在这个例子中,字符串"Hello World"被分割成了两个子字符串"Hello"和"World",并且存储在一个字符串数组strArr中。其中,正则表达式"\\s+"表示匹配一个或多个空格。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)