所以基本上不能/允许创建一个新数组。除了实际更改和操作当前数组外,无法返回任何内容。您如何获取字符数组并简单地翻转/反转它们。
Starting array: ['P','e','r','f','e','c','t',' ','M','a','k','e','s',' ','P','r','a','c','t','i','c','e']
反转每个单词,用空格隔开
Reversed: ['P','r','a','c','t','i','c','e',' ','M','a','k','e','s',' ','P','e','r','f','e','c','t']
这是我目前的情况
代码:
class Main {
public static void main(String[] args) {
char[] charArr = new char[] {'P','e','r','f','e','c','t',' ','M','a','k','e','s',' ','P','r','a','c','t','i','c','e'};
reverseCharArray(charArr);
}
public static void reverseCharArray() {
int arrLength = charArr.length;
for (int i = 0; i <= arrLength / 2; i++) {
charArr[arrLength - i - 1] = charArr[i];
System.out.println(charArr);
}
}
}
更新: 好的,我发现的是。我需要做的实际上是交换字符句子拼写的单词。使句子向后/颠倒。
注意:这是在此处的在线采访中尝试的: enter link description here
最佳答案
这绝对不是一个好的解决方案,但它是一个可行的解决方案。
class Main {
public static void main(String[] args) {
char[] charArr = new char[] { 'P', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'M', 'a', 'k', 'e', 's', ' ', 'P', 'r',
'a', 'c', 't', 'i', 'c', 'e' };
System.out.println(charArr);
reverseCharArray(charArr,0);
System.out.println(charArr);
}
public static void reverseCharArray(char[] charArr, int sorted) {
/* Look for last space*/
int lastSpace = -1;
for (int i = 0; i < charArr.length; i++) {
if (charArr[i] == ' ') {
lastSpace = i;
}
}
/* Grab the word and move it at the beginning of the sorted array */
for (int i = lastSpace + 1; i < charArr.length; i++) {
int k = i;
while (k != sorted) {
char tmp = charArr[k-1];
charArr[k-1] = charArr[k];
charArr[k] = tmp;
k--;
}
sorted++;
}
/* At this point, the last character is a space*/
/* Else, we've swapped all the words */
int k = charArr.length - 1;
if (charArr[k] != ' ') {
return;
}
/* If it's a space, grab it and move it at the beginning*/
while (k != sorted) {
char tmp = charArr[k-1];
charArr[k-1] = charArr[k];
charArr[k] = tmp;
k--;
}
sorted++;
/*Recursive call on the not sorted array*/
reverseCharArray(charArr,sorted);
}}
关于java - 如何在 Java 中交换字符数组(就地),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783685/