简体   繁体   English

反转字符串而不更改Java中的空格

[英]Reverse the string without changing white spaces in java

I'm working on reversing the string word by word and making sure that all the spaces, tabs and white spaces character etc. are not changed or removed. 我正在逐字反转字符串,并确保所有空格,制表符和空白字符等均未更改或删除。 I have tried few solution using Java, but ending up with no good result. 我已经尝试过使用Java的几种解决方案,但是最终都没有得到很好的结果。 For example , to convert following string 例如,转换以下字符串

 The rule       about++[]      the     input

        stream.

And get output like this without removing any white space character. 并在不删除任何空格字符的情况下获得这样的输出。

 ehT elur       tuoba++[]      eht     tupni

        maerts.

My code 我的密码

String reverseString(String str) {
    StringBuilder temp = new StringBuilder();
    StringBuilder result = new StringBuilder();
    for (char ch : str.toCharArray()) {
        if (Character.isAlphabetic(ch)) {
            temp.append(ch);
        } else {
            result.append(temp.reverse()).append(ch);
            temp.delete(0, temp.length());
        }
    }
    result.append(temp);
    return result.toString();
}

I getting same result with one issue that word about++[] , should be ][++tuoba0 where as it is showing like this tuoba++[] . 我在一个问题上得到了相同的结果, about++[]单词应该是][++tuoba0 ,因为它像这样的tuoba++[] Any way to resolve this issue? 有什么办法解决这个问题?

+ and [] are not alphabetical, so you are treating them the same way you treat whitespace. +[]并非按字母顺序排列,因此您对待它们的方式与处理空格相同。 Character.isWhitespace can help you solve your problem. Character.isWhitespace可以帮助您解决问题。

Try changing 尝试改变

if (Character.isAlphabetic(ch)) {

to

if (!Character.isWhitespace(ch)) {

This way you will include all characters that are not whitespaces. 这样,您将包括所有非空格字符。 Otherwise you will reverse only alphabetic characters which [ ] + are not. 否则,您将只反转不是[ ] +字母字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM