删除空格和大写第一个字母

时间:2017-12-04 18:50:17

标签: java uppercase

我做了这个程序,它将转过如下句子: 用户输入:你好,我饿了。冰箱在哪里。 系统输出:饿了我是你好。冰箱就在哪里。

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

    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  . 

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

好的,从您的代码中获取不太吸引人的内容,您的代码中有一个错误导致您遇到麻烦:

__iter__()

最后删除分号,并且在点之前不会有空格。

答案 2 :(得分:0)

这是我的方式。执行大量低效的字符串连接,并处理句号,问号和感叹号。

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();
}