在Java中,将空格插入字符数组可以通过以下几种方法实现:
1. 使用`String.format()`方法:
char[] array = new char;String format = "%-10s";String str = "Hello";System.arraycopy(str.toCharArray(), 0, array, 0, str.length());System.arraycopy(new String(new char[]{ ' ' }).toCharArray(), 0, array, str.length(), 1);System.out.println(new String(array));
2. 使用`StringBuilder`类:
StringBuilder sb = new StringBuilder();sb.append("Hello");sb.append(" ");System.out.println(sb.toString());
3. 使用`Arrays.fill()`方法:
char[] array = new char;Arrays.fill(array, ' ');array = 'H';System.out.println(new String(array));

4. 将字符串转换为字符数组,并在适当的位置插入空格:
String str = "Hello";char[] array = str.toCharArray();array = ' ';System.out.println(new String(array));
5. 使用两层循环将空格移动到数组的末尾:
public class BlankFilter {public static void forFilter(char[] arr) {for (int i = 0; i < arr.length; i++) {if (arr[i] == ' ') {for (int j = i; j < arr.length; j++) {if (arr[j] != ' ') {char temp = arr[i];arr[i] = arr[j];arr[j] = temp;}}}}}public static void main(String[] args) {char[] array = "Hello World".toCharArray();forFilter(array);System.out.println(new String(array));}}
以上方法都可以在字符数组中插入空格,具体选择哪种方法取决于你的具体需求和场景。如果你需要频繁修改字符串,使用`StringBuilder`会更高效。如果你需要将空格插入到特定位置,可以使用`String.format()`或直接操作字符数组。
