保留字符串的空格中每个单词的反向字符

时间:2018-07-26 03:02:47

标签: java

我有一个字符串,内容如下:

String sentence = "Book on the table but not over there \n" + 
                  "Almost there\r" +
                  "Have fun!"

我希望输出为

                  "kooB no eht elbat tub ton revo ereht \n" +
                  "tsomlA ereht\r"+
                  "evaH !nuf"

但是使用下面的代码输出

                 "kooB no eht elbat tub tno revo ehtre \n" +
                 "tsomlA ehtre\r"+
                 "evaH !nuf"

如何完成所需的输出?

注意:第一行的末尾有一个空格。

private static String reverseWords(String sentence) {
    HashMap<String, String> wordChain = new HashMap<>();
    try {
        String line = null;
        BufferedReader reader = new BufferedReader(new StringReader(sentence));
        while ((line = reader.readLine()) != null){
            String[] words = line.split(" ");
            for(int i=0; i<words.length; i++){
                String word = words[i];
                wordChain.put(word, reverseCharacters(word));
            }
            for(String key: wordChain.keySet()){
                sentence = sentence.replace(key, wordChain.get(key));
            }

        }

    } catch(IOException e){
        e.printStackTrace();
    }
    return sentence;
}

public static String reverseCharacters(String word){
    StringBuilder sb = new StringBuilder();
    for(int i = word.length()-1; i >=0; i--){
        sb.append(word.charAt(i));
    }
    return sb.toString();
}

6 个答案:

答案 0 :(得分:2)

尝试一下,您实际上不必重新发明反向逻辑:

public static String reverseCharacters(String word){
    return new StringBuilder(word).reverse().toString();
}

编辑:Complete code,保留空白。

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String sentence = "Book on the table but not over there \nAlmost there\rHave fun!";
        System.out.println(sentence);
        final char[]letters=sentence.toCharArray();
        final StringBuilder reversed = new StringBuilder();
        final StringBuilder tmp = new StringBuilder();
        for(char c:letters)
        {
            if(Character.isWhitespace(c))
            {
                reversed.append(tmp.reverse()).append(c);
                if(0 < tmp.length())
                {
                    tmp.delete(0,tmp.length());
                }
            }
            else
            {
                tmp.append(c);
            }
        }
        if(0 < tmp.length())
        {
            reversed.append(tmp.reverse());
        }
        System.out.println(reversed);
    }
}

答案 1 :(得分:0)

当您反转items: { xtype: 'form', reference: 'form', items: [{ xtype: 'textfield', name: 'username', fieldLabel: 'Username', allowBlank: false }, { xtype: 'textfield', name: 'password', inputType: 'password', fieldLabel: 'Password', allowBlank: false }, { xtype: 'button', text: 'Login', formBind: true, style: { marginTop: '10px', padding: '5px 15px 5px 15px' }, listeners: { click: 'onLoginClick' } }] } 时,您将得到no-如果将on替换为no,则您在{strong> {{1} } 也将被替换,从而产生 on 。当您检查on不存在之后,但是您希望tontno取代,所以不能。

尝试在反向时添加反向词,例如:

ton

答案 2 :(得分:0)

问题是您在替换单词时不考虑空格。 例如wordChain的on-> no和not-> ton。因此,在替换时,请'not'->'ton'->'tno'。

答案 3 :(得分:0)

您的问题是let A = [{ text: '故事', value: 'story', }, { text: '诗歌', value: 'poetry', }, { text: '励志', value: 'inspirational', } ]; // array B from backend** let B = { story: 2, poetry: 34, inspirational: 30, }; A.sort((a, b) => B[b.value] - B[a.value]); console.log(A);。首先,您拥有sentence = sentence.replace(key, wordChain.get(key));,然后将单词there替换为the,现在您的单词eht变成了there

最简单的方法是将每个反向单词连成一个新句子。

ehtre

答案 4 :(得分:0)

我同意zhh,原因是 import { Directive, Input, ElementRef } from '@angular/core'; @Directive({ selector: '[delayFocus]' }) export class DelayFocusDirective { @Input() delayFocusInterval; @Input() set delayFocus(condition: boolean) { if (condition) { console.log(this.delayFocusInterval); setTimeout(() => { this.el.nativeElement.focus(); }, this.delayFocusInterval | 500); } } constructor(private el: ElementRef) { } } 将替换句子中的所有单词,因此您可能会看到“那里”也包括“ the”,因此这里您仅在“那里” =>“ ehtre”上遇到了问题

答案 5 :(得分:0)

这里是完整的代码,以获得所需的输出。这分为三个步骤:

  1. 创建非空格字符串(单词)和空格 字符串(空格词)并将其存储在相应的字符串中 List<String>个收藏集。
  2. 字符串中的单词是相反的(例如Book-> kooB)。
  3. 将反向词和空格词组合起来以得到结果。
  4. (可选)验证空白是否保留。

注意:空格由Character.isWhitespace()定义。

import java.util.*;
import java.io.*;

public class ReverseTextTest {

    private static String sentence =
        "Book on the table but not over there \n" + 
        "Almost there\r" +
        "Have fun!";                    
    private static List<String> whitespaceWords = new ArrayList<>();

    public static void main(String [] args) throws IOException {
        // Build words and store whitespaces
        List<String> words = getWords();
        System.out.println(words);
        // Build the reversed words
        List<String> wordsReversed = getReversedWords(words);
        System.out.println(wordsReversed);
        // Assemble reversed words and the whitespaces
        String result = assembleWordsAndWhitespaces(wordsReversed);
        System.out.println(result);
        // Verification
        printToVerify(result);
    }

    /*
     * Accepts input string of words containing character words and
     * whitespace(s) (as defined in the method Character#isWhitespce method).
     * Processes and returns only the character strings. And, stores the
     * whitespace 'words' (a single or multiple whitespaces) in a List<String>.
     * NOTE: This method uses String concatenation in a loop. For processing
     * larger inputs consider using a StringBuilder.
     * NOTE: The whitespace is as defined in the Character.isWhitespace()
     * https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html.
     */
    private static List<String> getWords()
            throws IOException {
        List<String> words = new ArrayList<>();
        String word = "";
        String whitespaceWord = "";
        boolean wordFlag = true;
        StringReader reader = new StringReader(sentence);
        for (int i = 0; i < sentence.length(); i++) {
            char c = (char) reader.read();
            if (! Character.isWhitespace(c)) {
                if (! wordFlag) {
                    wordFlag = true;
                    whitespaceWords.add(whitespaceWord);
                    word = whitespaceWord = "";
                }
                word = word + String.valueOf(c);
            }   
            else {
                if (wordFlag) {
                    wordFlag = false;
                    words.add(word);
                    word = whitespaceWord = "";
                }
                whitespaceWord = whitespaceWord + String.valueOf(c);
            }
        } // end-for
        reader.close();
        if (! whitespaceWord.isEmpty()) {
            whitespaceWords.add(whitespaceWord);
        }
        if (! word.isEmpty()) {
            words.add(word);
        }
        return words;
    }

    private static List<String> getReversedWords(List<String> words) {
        words.replaceAll(word -> getReversedWord(word)); // can also use a for-loop
        return words;
    }   

    private static String getReversedWord(String word) {
        StringBuilder sbWord = new StringBuilder(word);
        return sbWord.reverse().toString();
    }

    private static String assembleWordsAndWhitespaces(List<String> wordsReversed) {
        String resultString = "";
        char firstChar = sentence.charAt(0);
        if (Character.isWhitespace(firstChar)) {
            // The text start with whitespace
            for (int i = 0; i < whitespaceWords.size(); i++) {
                resultString = resultString.concat(whitespaceWords.get(i));
                if (i < wordsReversed.size()) {
                    resultString = resultString.concat(wordsReversed.get(i));
                }
            }
        }
        else {
            // The text start with alpha word
            for (int i = 0; i < wordsReversed.size(); i++) {
                resultString = resultString.concat(wordsReversed.get(i));
                if (i < whitespaceWords.size()) {
                    resultString = resultString.concat(whitespaceWords.get(i));
                }
            }
        }
        return resultString;
    }

    // This is to verify that the whitespaces are substituted correctly.
    // This prints with "\n" and "\r" literals substituted 
    // for \n (linefeed) and \r (carriage return) respectively.
    // For example: "abc \n xyz" will print literally as: abc \n xyz
    private static void printToVerify(String result) {
        for (int i = 0; i < result.length(); i++) {
            char c = result.charAt(i);
            if (c == ("\r".charAt(0))) {
                System.out.print("\\r");
            }
            else if (c == ("\n".charAt(0))) {
                System.out.print("\\n");
            }
            else {
                System.out.print(c);
            }
        }
        System.out.println("");
    }
}