【问题标题】:Remove space and Uppercase first letter删除空格和大写首字母
【发布时间】:2017-12-04 18:50:17
【问题描述】:

我制作了这个程序,它可以转换以下句子: 用户输入:你好,我饿了。冰箱在哪里。 系统输出:Hungry i´m Hello。冰箱是哪里。

但最后一个单词和“.”之间有空格。在倒置的句子中。我怎样才能删除?我怎样才能使第一个单词成为大写单词?

    package etzale;


public class etzale {




    public static void main(String[] args) {


        StringBuilder outputString= new StringBuilder();

        String satz;


        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}

如何删除最后一个单词和“。”之间的空格。每个句子都有?

Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  . 

【问题讨论】:

  • 你的代码真的很糟糕,德语无助于让它更具吸引力:D,你还有 if 语句什么都不做: outputString.append(s[i]) ;
  • 另请阅读下面的我的答案,如果它有助于修复您的代码,请将答案标记为好:)

标签: java uppercase


【解决方案1】:

我已经回答了另一个你几乎类似的问题:Reverse all words, set "." and do the same for the next sentences,我的解决方案涵盖了这个案例也试试吧:

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        final String userInput = "Hello i´m hungry. Where is the fridge.";
        final String expectedResult = "Hungry i´m Hello. Fridge the is Where.";
        String[] sentences = userInput.split("\\. ");
        String reversedSentences = Stream.of(sentences)
                .map(sentenceString -> new Sentence(sentenceString))
                .map(Sentence::reverse)
                .map(Sentence::firstLetterToUpperCase)
                .map(Sentence::removeAllDots)
                .map(Sentence::dotInTheEnd)
                .map(Sentence::toString)
                .collect(Collectors.joining(" "));
        System.out.println(reversedSentences.equals(expectedResult)); //returns true
    }


}

final class Sentence {
    private final String sentence;

    Sentence(String sentence) {
        this.sentence = sentence;
    }

    Sentence reverse() {
        String[] words = sentence.split(" ");
        Collections.reverse(Arrays.asList(words));
        return new Sentence(String.join(" ", words));
    }

    Sentence firstLetterToUpperCase() {
        String firstLetter = sentence.substring(0, 1);
        String anotherPart = sentence.substring(1);
        return new Sentence(firstLetter.toUpperCase() + anotherPart);
    }

    Sentence dotInTheEnd() {
        return new Sentence(sentence + ".");
    }

    Sentence removeAllDots() {
        return new Sentence(sentence.replaceAll("\\.", ""));
    }

    public String toString() {
        return sentence;
    }
}

【讨论】:

    【解决方案2】:

    好的,除了你的代码不是很吸引人之外,你的代码中有一个错字给你带来了麻烦:

    outputString.append(" ");
    

    去掉最后的分号,点前就没有空格了。

    【讨论】:

    • 你确定吗?那么s[0]==" "呢?
    • 没有仔细阅读代码,只是注意到一个明显的错字,修复它并且输出看起来不错,所以我发布了一个答案。
    【解决方案3】:

    我会这样做。执行低效的字符串连接,并处理句号、问号和感叹号。

    public static void main(String[] args) {
        System.out.println("Bitte geben Sie einen String ein: ");
        String text = "Hallo mir gehts gut!! Wie gehts dir. mir gehts spitze.";
    
        System.out.println(reverseSentences(text));
    }
    
    /**
     * Reverse the order of the words in the sentence.
     * @param sentence the sentence to reverse.
     * @param terminal the symbol to add at the end.
     * @return the reversed sentence, with added terminal.
     */
    static String reverse(String sentence, String terminal) {
        sentence = sentence.trim();
        if (sentence.isEmpty()) {
            return terminal;
        }
    
        // find words by splitting the sentence at spaces
        // then put the words back together in reverse order
        String[] words = sentence.split("\\s+");
        StringBuilder sb = new StringBuilder(sentence.length());
    
        for (int i = words.length - 1; i >= 0; i--) {
            String word = words[i];
            // capitalize the last word before placing it at the start
            if (i == words.length - 1 && !word.isEmpty()) {
                sb.append(word.substring(0, 1).toUpperCase());
                sb.append(word.substring(1));
            } else {
                sb.append(word);
            }
            if (i > 0) sb.append(' ');
        }
    
        // append terminal
        sb.append(terminal);
        return sb.toString();
    }
    
    /**
     * Reverse each sentence in the string.
     * @param s the string to act on.
     * @return the string, with sentences reversed.
     */
    public static String reverseSentences(String s) {
        // Match each sentence, with an optional terminal
        // terminal may be one or more
        // full stops, question or exclamation marks
        Pattern p = Pattern.compile("([^.?!]+)([.?!]*)");
        Matcher m = p.matcher(s);
    
        // find and reverse the sentences, then recombine them
        StringBuilder sb = new StringBuilder(s.length());
        while (m.find()) {
            String sentence = m.group(1);
            String terminal = m.group(2);
            sb.append(reverse(sentence, terminal));
            sb.append(' ');
        }
    
        return sb.toString().trim();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2020-05-21
      • 1970-01-01
      • 2016-04-23
      • 2021-07-29
      • 2011-05-14
      • 1970-01-01
      相关资源
      最近更新 更多