简体   繁体   English

我如何在 Java 中使用字符串反转大写和逐行分隔单词?

[英]How do i Reverse Capitalize And Separate Words By Line Using String In Java?

The input is: i love cake输入是: i love cake

The output needs to be: Cake Love I输出需要是: Cake Love I

But the actual result is: I Love Cake但实际结果是: I Love Cake

What I've got:我有什么:

import java.util.regex.Pattern; 
public class yellow {

    static String reverseWords(String str){
        Pattern pattern = Pattern.compile("\\s");
        String[] temp = pattern.split(str);
        String result = "";

        for (int i = 0; i < temp.length; i++) {
            if (i == temp.length - 1)
                result = temp[i] + result;
            else
                result = " " + temp[i] + result;
        }
        return result;
    }

    public static void main(String[] args){
        String source = "i love cake";
        StringBuffer res = new StringBuffer();

        String[] strArr = source.split(" ");
        for (String str : strArr) {
            char[] stringArray = str.trim().toCharArray();
            stringArray[0] = Character.toUpperCase(stringArray[0]);
            str = new String(stringArray);

            res.append(str).append(" ");
        }
        System.out.print(res.toString());
    }
}

What am I doing wrong?我究竟做错了什么?

for (String str : strArr) {

}

This loops forward.这向前循环。 What you want is to loop backwards, or to place elements into the string backwards.您想要的是向后循环,或者向后将元素放入字符串中。 I recommend you loop backwards and print as you go:我建议您向后循环并随时打印:

for (int i = strArr.length - 1; i >= 0; i--) {
    char[] stringArray = strArr[i].trim().toCharArray();
    stringArray[0] = Character.toUpperCase(stringArray[0]);
    System.out.println(new String(stringArray));
}

Or, you could use that convenient reverseWords method that you never use anywhere... though looping backwards is faster.或者,您可以使用那种在任何地方都从未使用过的方便的reverseWords方法……尽管向后循环更快。 Probably.大概。

[EDITED] Call this for each line with string s, then print a line break (If you have multiple sentences & expect them in their own lines). [已编辑] 用字符串 s 为每一行调用它,然后打印一个换行符(如果你有多个句子并期望它们在自己的行中)。

void reverseCamel(String s){
    String[] ar = s.split("\\s+");
    for(int i = ar.length - 1;i>=0;i--){
        ar[i][0] = Character.toUpperCase(ar[i][0]);
        System.out.print(ar[i] + " ");
    }
}

Here is what i did.这是我所做的。

public class Main {

public static void main(String[] args) {
    reverse("I Love Cake");
}

public static void reverse( String string){
    String[] word =string.split(" "); // split by spaces
    int i = word.length-1;
    while (i>=0){
       // System.out.print(word[i].toUpperCase()+" ");//if you want in upper case
        System.out.print(word[i]+" ");
        i--;
      }
   }
}

First of all you have to reverse the String.首先,您必须反转字符串。

String[] words = source.split("\\s");
String reversedString = "";
for(int i = words.length -1; i>=0; i--){
    reversedString += words[i] + " ";
}

Then, you know that the ASCII code of 'a' character is 97, 'A' is 65. To convert from lower case to capital you substract 32. All capitals are between 65 and 92. All small letters are between 97 and 124. You want to capitalize only letters at the beginning of a word (preceded by a space or first letter).那么,你知道'a'字符的ASCII码是97, 'A'是65。小写转大写要减去32。所有大写字母都在65到92之间,所有小写字母都在97到124之间。您只想将单词开头的字母大写(前面有空格或第一个字母)。

String capitalCase = "";
        for (int i = 0; i < reversedString.length(); i++) {
            char c = reversedString.charAt(i);
            if (c >= 97 && c <= 124) {
                if (i == 0) c -= 32;
                else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
            }
            capitalCase += c;
        }

And here you go now System.out.println(capitalCase);现在开始System.out.println(capitalCase);

Overall, you will have the following code:总的来说,您将拥有以下代码:

import java.util.Scanner;

public class yellow {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.println("Enter a string:");
        String source = s.nextLine();

        String[] words = source.split("\\s");
        String reversedString = "";
        for (int i = words.length - 1; i >= 0; i--) {
            reversedString += words[i] + " ";
        }

        String capitalCase = "";
        for (int i = 0; i < reversedString.length(); i++) {
            char c = reversedString.charAt(i);
            if (c >= 97 && c <= 124) {
                if (i == 0) c -= 32;
                else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
            }
            capitalCase += c;
        }

        System.out.println(capitalCase);
    }
}

Output:输出:

Enter a string:
i love cake
Cake Love I 

Java 8 * Apache Commons Lang Java 8 * Apache Commons Lang

public static String reverseWordsInString(String str) {
    List<String> words = Pattern.compile("\\s+").splitAsStream(str)
                                .map(StringUtils::capitalize)
                                .collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
    return words.stream().collect(Collectors.joining(StringUtils.SPACE));
}

Java 8爪哇 8

public static String reverseWordsInString(String str) {
    List<String> words = Pattern.compile("\\s+").splitAsStream(str)
                                .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
                                .collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
    return words.stream().collect(Collectors.joining(" "));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM