java实现一个方法:接受一个字符窜和一个正整数作为参数,将该字符串每n个字符分组,并返回,实现用法
时间: 2024-05-20 18:15:57 浏览: 8
public static List<String> groupString(String str, int n) {
List<String> result = new ArrayList<>();
int length = str.length();
for (int i = 0; i < length; i += n) {
if (i + n < length) {
result.add(str.substring(i, i + n));
} else {
result.add(str.substring(i));
}
}
return result;
}
// 使用方法
String str = "abcdefghijk";
int n = 3;
List<String> groupList = groupString(str, n);
for (String group : groupList) {
System.out.println(group);
}
// 输出结果:abc def ghi jk
相关问题
Java实现一个方法:接受一个字符串和一个正整数n作为参数,将该字符串每n个字符分组,并返回由这些分组构成的字符串数组。
以下是Java实现的代码:
```java
public static String[] groupString(String str, int n) {
if (str == null || str.length() == 0 || n <= 0) {
return new String[0];
}
int len = str.length();
int groupCount = (len + n - 1) / n; // 计算分组个数
String[] result = new String[groupCount];
for (int i = 0; i < groupCount; i++) {
int start = i * n;
int end = Math.min(start + n, len);
result[i] = str.substring(start, end);
}
return result;
}
```
使用示例:
```java
String str = "abcdefg";
int n = 3;
String[] result = groupString(str, n);
System.out.println(Arrays.toString(result)); // ["abc", "def", "g"]
```
实现一个方法:接受一个字符串和一个正整数n作为参数,将该字符串每n个字符分组,并返回由这些分组构成的字符串数组。
def split_string(string, n):
result = []
for i in range(0, len(string), n):
result.append(string[i:i+n])
return result
# 例子
print(split_string("1234567890", 3)) # ['123', '456', '789', '0']
print(split_string("abcdefghij", 4)) # ['abcd', 'efgh', 'ij']
print(split_string("abcdef", 2)) # ['ab', 'cd', 'ef']
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)