期间是句子反转者的一个空间

时间:2017-11-08 17:31:56

标签: java

我的句子翻转中有问题。

  

输入:玛丽有一只小羊羔。它的羊毛像雪一样白   期望的输出:羔羊很少有玛丽。白雪皑皑的雪   实际产量:羊羔很少有玛丽。雪白如羊毛。

正如您所看到的,这些时期是一个空间。它应该与所需输出的外观完全一致。我应该调整什么来获得所需的输出?

import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Pattern;
public class SentenceReverser {
    // main method
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.printf("1. Enter string to reverse : ");
        String inputString = scanner.nextLine();
        if (inputString == null || inputString.length() == 0) {
            System.out.println("Enter the valid string");
            return;
        }
        String reverse = reverseStringWordWise_Stack(inputString);
        System.out.printf("\n3. Reverse string using stack is : %s", reverse);
    }
    // reverses the string using a stack
    private static String reverseStringWordWise_Stack(String inputString) {
        String[] fullstopString = inputString.trim().split(Pattern.quote("."));
        StringBuilder finalBuilder = new StringBuilder();
        for (String fullstop : fullstopString) {
            String[] arrString = fullstop.trim().split(Pattern.quote(" "));
            Stack stack = new Stack();
            for (String input : arrString) {
                if (input.endsWith(".")) {
                    stack.push(input.toLowerCase().substring(0, input.length() - 1));
                    break;
                } else {
                    stack.push(input);
                }
            }
            StringBuilder builder = new StringBuilder();
            while (!stack.isEmpty()) {
                if (stack.size() == 1) {
                    String element = stack.pop().toString();
                    builder.append(element.substring(0, 1).toLowerCase() + element.substring(1)).append(" ");
                } else {
                    builder.append(stack.pop()).append(" ");
                }
            }
            builder.append(".");
            String result = builder.substring(0, 1).toUpperCase() + builder.substring(1);
            finalBuilder.append(result);
        }
        return finalBuilder.toString();
    }
}

1 个答案:

答案 0 :(得分:1)

您在if语句中添加到句子的最后一个单词后面放置一个空格:

if (stack.size() == 1) {
        String element = stack.pop().toString();
        builder.append(element.substring(0, 1).toLowerCase() + 
        element.substring(1)).append(" ");
}

你应该在那里放一段时间:

if (stack.size() == 1) {
        String element = stack.pop().toString();
        builder.append(element.substring(0, 1).toLowerCase() + 
        element.substring(1)).append(".");
}