Java 将字符[]/句子中的单词颠倒过来
我想使用常量空格反转字符串中的单词。问题是单词不能包含连续的空格。我希望将单词之间的所有连续空格减少为一个空格,同时忽略前导空格和尾随空格。我能够实现单词的就地反转,但我正在努力实现删除单词之间的连续空格以及前导空格和尾随空格。有人能帮我吗 以下是我到目前为止的情况:Java 将字符[]/句子中的单词颠倒过来,java,string,reverse,Java,String,Reverse,我想使用常量空格反转字符串中的单词。问题是单词不能包含连续的空格。我希望将单词之间的所有连续空格减少为一个空格,同时忽略前导空格和尾随空格。我能够实现单词的就地反转,但我正在努力实现删除单词之间的连续空格以及前导空格和尾随空格。有人能帮我吗 以下是我到目前为止的情况: public char[] reverseWords(char[] s) { if (s == null) return null; int right = 0; s = rever
public char[] reverseWords(char[] s) {
if (s == null)
return null;
int right = 0;
s = reverseString(s, 0, s.length - 1);// get the reversed sentence
//System.out.println(s);
for (int left = 0; left < s.length; left++) {
if (s[left] != ' ') {// for first word
for (right = left; right < s.length && s[right] != ' '; right++)
; // get end of word
s = reverseString(s, left, right - 1);
left =(right - 1);// move left index to end of
// word
// s[left++] = ' ';
}
}
return s;
}
public char[] reverseString(char[] strChars, int start, int end) {
if (strChars == null)
return null;
while (start < end) {
char temp = strChars[start];
strChars[start] = strChars[end];
strChars[end] = temp;
start++;
end--;
}
return strChars;
}
将会有更简单/更快的方法。我只是在想一个应该有利于学习目的的想法 首先,做你现在所做的一切,将单词颠倒过来,并保持连续的空格不变 然后编写另一个方法来执行连续的空格删除 有两个指针,从第一个位置开始,该位置不是空格 A和B继续一起前进 如果是B、 然后我们做s[A]=s[B];s[B]='' 如果s[A]和s[A-1]是空间,那么A站A现在在第二个空间,只有B继续向前移动。通过这种方式,A将保持相同的位置并继续从B复制,直到B给出一个非空格字符 当B到达终点时,它就结束了 在psuedo代码中,它类似于
int a = first position of non-space;
int b = a;
while b < s.size() {
if (a != b) {
s[a] = s[b]
s[b] = ' '
}
if (both s[a] and s[a-1] are space) {
increment b;
// leave a untouched
} else {
increment a;
increment b;
}
}
第一个反转很小,所以我跳过它。提示是,对于第二个单词,您将在第一个空格之后的位置停止L:
cba def ghi
L
反面的右侧将是单词的第一个右边界:
cba def ghi
L R
然后在适当的位置执行相反的操作
cba fed ghi
L R
然后继续寻找L的下一个位置以再次开始反转:
cba fed ghi
L
采取类似的逻辑
cba fed ghi
L R
然后
一个非常简单的单线解决方案是使用。我有两种方法,我使用and方法。下面是:
String line = " Hello World! ";
line = line.replaceAll(" +", " "); // '+' = 1 or more i.e. at least 1.
// Hence it replaces ALL white spaces with a single space.
line = line.trim(); //This 'trims' the String to remove all leading and trailing
// whitespaces.
System.out.println(line); //Output: "Hello World!"
更普遍的做法是使用\\s+而不是。实际上,字符是\s,但在存储到字符串中时应使用双斜杠。你仍然会得到同样的结果。您也可以尝试使用-方法。是的,您将如何使用整个句子的字符数组来实现这一点?对。我以为你的问题是字符串。我的错。你能做一个.replace吗?@Aarowaim chars没有方法…在你删除了连续的空格后,你想用什么填充结尾的额外字符?
cba fed ihg
L R
String line = " Hello World! ";
line = line.replaceAll(" +", " "); // '+' = 1 or more i.e. at least 1.
// Hence it replaces ALL white spaces with a single space.
line = line.trim(); //This 'trims' the String to remove all leading and trailing
// whitespaces.
System.out.println(line); //Output: "Hello World!"