在java中反转字符串数组

时间:2015-04-12 18:13:37

标签: java arrays

我需要制作一个程序,用一个用户输入的句子并用适当的格式和标点符号反转它。

Ex:快速的棕色狐狸跳过懒狗。

结果:"狗懒得过快跳过狐狸棕色。"

我已经看到了这方面的解决方案,我可以通过一次询问用户一个字来得到正确的答案。但是我们特别要求我们只询问用户的句子,然后程序完成其余的工作。所以程序必须确定数组的大小,并将字符串中的每个单词分配给数组中的值(我猜?)。

到目前为止,这就是我所拥有的,但我认为我需要使用stringBuffer,但我不知道如何实现它。

public class ReverseSentence {

    public static void main(String[] args) {






        String[] sentence = new String[]{IO.readString()};

        for(int counter = 0; counter < sentence.length; counter++){
            System.out.println("Enter Sentence"+(counter+1));
            sentence[counter] = IO.readString();
        }

        System.out.println("The Reversed Sentence is:");
        for(int counter = sentence.length - 1; counter >= 0; counter--){
            System.out.print(sentence[counter]);

        }





    }

}

这不是作业作业,只是即将到来的考试的一些练习题,所以完整的解决方案会没问题,但如果可能的话,请注释,这样我就可以看到你是如何做到的。

4 个答案:

答案 0 :(得分:2)

您可以尝试这样:

public static String reverseString(String input) {
     //from input to this method
     // split input with space and store words
     // in a collection if input is not empty
    Deque<String> words = new ArrayDeque<>();
    for (String word: input.split(" ")) {
        if (!word.isEmpty()) {
            words.addFirst(word);
        }
    }

      //now build output in reverse order of
      // addition to collection if input is not empty
    StringBuilder result = new StringBuilder();
    while (!words.isEmpty()) {
        result.append(words.removeFirst());
        if (!words.isEmpty()) {
            result.append(" ");
        }
    }
    return result.toString();
}

答案 1 :(得分:2)

你有两个不同的问题:

  1. 撤回句子
  2. 将句子大写
  3. 让我们先做第一部分:

    public static String reverseSentence(final String sentence) {
        final Pattern pattern = Pattern.compile("[^A-Za-z']+");
        final List<String> words = pattern.splitAsStream(sentence)
                .map(String::toLowerCase)
                .collect(toList());
        final StringBuilder reversed = new StringBuilder();
        final ListIterator<String> i = words.listIterator(words.size());
        reversed.append(i.previous());
        while (i.hasPrevious()) {
            reversed
                    .append(" ")
                    .append(i.previous());
        }
        reversed.append(".");
        return reversed.toString();
    }
    

    仔细检查代码:

    public static void main(String[] args) throws Exception {
        System.out.println(reverseSentence("The quick brown fox jumps over the lazy dog"));
    }
    
      狗懒得快跳过狐狸褐色。

    好的,现在我们需要把第一个词大写:

    public static String capitalise(final String name) {
        return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
    }
    

    我们只需要在第一个单词上使用此方法:

    public static String reverseSentence(final String sentence) {
        final Pattern pattern = Pattern.compile("[^A-Za-z']+");
        final List<String> words = pattern.splitAsStream(sentence)
                .map(String::toLowerCase)
                .collect(toList());
        final StringBuilder reversed = new StringBuilder();
        final ListIterator<String> i = words.listIterator(words.size());
        reversed.append(capitalise(i.previous()));
        while (i.hasPrevious()) {
            reversed
                    .append(" ")
                    .append(i.previous());
        }
        reversed.append(".");
        return reversed.toString();
    }
    

    再次检查:

      狗懒得快跳过狐狸褐色。

答案 2 :(得分:0)

使用Apache Commons StringUtils。

https://commons.apache.org/proper/commons-lang/

String result = StringUtils.capitalize(StringUtils.reverse(StringUtils.uncapitalize(basicString.substring(0,basicString.length()-1)))) + ".";

答案 3 :(得分:0)

试试这个。此代码将使用句点(。)给出所有格式的输出。并仔细阅读评论。

Scanner inp = new Scanner(System.in);

String s1 = inp.nextLine();
String s2[] = s1.split(" ");
boolean full_stop = false;
// Printing first character of last string in upper case
System.out.print(Character.toUpperCase(s2[s2.length - 1].charAt(0)));
// Printing rest of the character of last string
if (s2[s2.length - 1].contains(".")) {// checking that (.) is exists then print without (.)
    System.out.print(s2[s2.length - 1].substring(1,s2[s2.length - 1].length() - 1) + " ");
    full_stop = true;
} else {
    System.out.print(s2[s2.length - 1].substring(1, s2[s2.length - 1].length()) + " ");
}
for (int i = s2.length - 2; i >= 0; i--) {
    if (i > 0) {
        System.out.print(s2[i] + " ");
    } else {
        System.out.print(Character.toLowerCase(s2[i].charAt(0)));//converting first string character to lower case
        System.out.print(s2[i].substring(1,s2[i].length()));// last string must not have space after that
    }
}
if (full_stop) {// printing (.) if exists
    System.out.println(".");
}