反转“Hello World”的每个单词Java 中的字符串

发布于 2024-08-25 05:38:31 字数 133 浏览 10 评论 0原文

我想反转 Java 中字符串的每个单个单词(不是整个字符串,只是每个单词)。

示例:如果输入字符串是“Hello World”,则输出应为“olleH dlroW”。

I want to reverse each individual word of a String in Java (not the entire string, just each individual word).

Example: if input String is "Hello World" then the output should be "olleH dlroW".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

○闲身 2024-09-01 05:39:00

简单的方法:

String reverseString(String string)
{
    String newString = "";
    for(int x = string.length() - 1; x > -1; x ++)
        newString += string.charAt(x);
    return newString;
}

Easy way:

String reverseString(String string)
{
    String newString = "";
    for(int x = string.length() - 1; x > -1; x ++)
        newString += string.charAt(x);
    return newString;
}
三人与歌 2024-09-01 05:38:59

这会反转给定字符串中的单词。假定单词之间由一个空格分隔。反转是就地完成的(在字符缓冲区中)。

public static String reversePhrases(String s)
{
    char[] buf = s.toCharArray();
    int len = buf.length;
    int start = 0;
    for (int i = 0; i < len; i++) {
        if (buf[i] == ' ' || i == (len-1)) {
            if (i == (len-1)) {
                i = len;
            }
            int end = (start + i)/2;
            for (int j = start; j < end; j++) {
                char c = buf[j];
                int pos = (start + i) - j - 1;
                buf[j] = buf[pos];
                buf[pos] = c;
            }
            start = i + 1;    
        }
    }
    return new String(buf);
}

This reverses the words in the given string. Words are assumed to be separated by a single space. Reversal is done in place (in the character buffer).

public static String reversePhrases(String s)
{
    char[] buf = s.toCharArray();
    int len = buf.length;
    int start = 0;
    for (int i = 0; i < len; i++) {
        if (buf[i] == ' ' || i == (len-1)) {
            if (i == (len-1)) {
                i = len;
            }
            int end = (start + i)/2;
            for (int j = start; j < end; j++) {
                char c = buf[j];
                int pos = (start + i) - j - 1;
                buf[j] = buf[pos];
                buf[pos] = c;
            }
            start = i + 1;    
        }
    }
    return new String(buf);
}
度的依靠╰つ 2024-09-01 05:38:57
String someString = new String("Love thy neighbor");
    System.out.println(someString);
    char[] someChar = someString.toCharArray();
    int j = someChar.length - 1;
    char temp;
    for (int i = 0; i <= someChar.length / 2; i++) {
        temp = someChar[i];
        someChar[i] = someChar[j];
        someChar[j] = temp;
        j--;
    }
    someString = new String(someChar);
    System.out.println(someString);

跑步:

Love thy neighbor
robhgien yht evoL
String someString = new String("Love thy neighbor");
    System.out.println(someString);
    char[] someChar = someString.toCharArray();
    int j = someChar.length - 1;
    char temp;
    for (int i = 0; i <= someChar.length / 2; i++) {
        temp = someChar[i];
        someChar[i] = someChar[j];
        someChar[j] = temp;
        j--;
    }
    someString = new String(someChar);
    System.out.println(someString);

Run:

Love thy neighbor
robhgien yht evoL
倾城花音 2024-09-01 05:38:54

流 API 示例

    public static String reverseAllWords(String str) {
    String[] arr = str.split(" ");
    String res = "";
    for (int x = 0; x < arr.length; x++) {
        res = res + Stream.of(arr[x].split("")).reduce("", (a, b) -> b + a) + " ";
    }
    return res;
}

example with stream API

    public static String reverseAllWords(String str) {
    String[] arr = str.split(" ");
    String res = "";
    for (int x = 0; x < arr.length; x++) {
        res = res + Stream.of(arr[x].split("")).reduce("", (a, b) -> b + a) + " ";
    }
    return res;
}
烛影斜 2024-09-01 05:38:54

您可以使用增强型 for 循环反转字符串并交换其中的加数:

public static String reverse(String str) {
    String revStr = "";
    for (char ch : str.toCharArray()) {
        // concat of chars in reverse order
        revStr = ch + revStr;
    }
    return revStr;
}
public static String[] reverse(String[] arr) {
    String[] revArr = new String[arr.length];
    for (int i = 0; i < arr.length; i++) {
        // same word order
        revArr[i] = reverse(arr[i]);
    }
    return revArr;
}
public static void main(String[] args) {
    String[] arr = reverse("Hello World".split(" "));
    System.out.println(String.join(" ", arr));
}

输出:

olleH dlroW

You can reverse a string using the enhanced for loop and swap the summands inside:

public static String reverse(String str) {
    String revStr = "";
    for (char ch : str.toCharArray()) {
        // concat of chars in reverse order
        revStr = ch + revStr;
    }
    return revStr;
}
public static String[] reverse(String[] arr) {
    String[] revArr = new String[arr.length];
    for (int i = 0; i < arr.length; i++) {
        // same word order
        revArr[i] = reverse(arr[i]);
    }
    return revArr;
}
public static void main(String[] args) {
    String[] arr = reverse("Hello World".split(" "));
    System.out.println(String.join(" ", arr));
}

Output:

olleH dlroW
羞稚 2024-09-01 05:38:53

逐块反向复制字符串,然后连接空格。
例如。 “你好java世界”。

第一个块=“hello”反向复制它:-“olleh”然后添加空格
第二块=“java”等。

public static void main(String args[]) {
    String s, rev = "";
    Scanner in = new Scanner(System.in);

    System.out.println("Enter a string to reverse");
    s = in.nextLine();

    int length = s.length();
    // char[] cs=s.toCharArray();
    int l, r;
    int i = 0;
    while (i < length) {
        l = i; // starting index
        // find length of sub-block to reverse copy
        while (i < length && s.charAt(i) != ' ') { 
            i++;
        }
        r = i - 1; // ending index
        for (int j = r; j >= l; j--) { // copy reverse of sub-block
            rev = rev + s.charAt(j);
        }
        rev = rev + " "; // add the whitespace
        i++;
    }

    System.out.println("Reverse of entered string is: " + rev);
}

程序也适用于单词之间的多个空格。

Reverse copy the string block-wise and then concatenate the whitespaces.
for eg. "hello java world".

1st block = "hello" reverse copy it:- "olleh" and add whitespace then
2nd block = "java" etc.

public static void main(String args[]) {
    String s, rev = "";
    Scanner in = new Scanner(System.in);

    System.out.println("Enter a string to reverse");
    s = in.nextLine();

    int length = s.length();
    // char[] cs=s.toCharArray();
    int l, r;
    int i = 0;
    while (i < length) {
        l = i; // starting index
        // find length of sub-block to reverse copy
        while (i < length && s.charAt(i) != ' ') { 
            i++;
        }
        r = i - 1; // ending index
        for (int j = r; j >= l; j--) { // copy reverse of sub-block
            rev = rev + s.charAt(j);
        }
        rev = rev + " "; // add the whitespace
        i++;
    }

    System.out.println("Reverse of entered string is: " + rev);
}

Program also works for multiple whitespaces between words.

煮茶煮酒煮时光 2024-09-01 05:38:53

上述一些解决方案的运行时复杂度较高。使用下面的算法,可以在 O(n) 时间内实现。

算法:

  1. 从头到尾解析字符串。
  2. 每次遇到空格字符,即“”,将到目前为止解析的字符列表放入一个可以动态增长的ArrayList中。
  3. 以相反的顺序打印 ArrayList,这将为您提供所需的输出。

复杂度:O(n),其中 n 是字符串的长度。

import java.io.IOException;
import java.util.ArrayList;

public class WordReverse {

    public static void main(String[] args) throws IOException {

        String inputStr = "Hello World";
        String reversed = "";
        ArrayList<String> alist = new ArrayList<String>();

        for (int i = inputStr.length() - 1; i >= 0; i--) {
            if (inputStr.charAt(i) != ' ') {
                reversed = reversed + inputStr.charAt(i);
            } else {
                alist.add(reversed);
                reversed = "";
            }
        }
        alist.add(reversed);
        String result = "";

        for (int i = alist.size() - 1; i >= 0; i--) {
            result = result + alist.get(i);
            result = result + " ";
        }
        System.out.println(result);
    }
}

Some of the above solutions are of the higher run time complexities. With the below algorithm, it can be achieved in O(n) time.

Algorithm:

  1. Parse the String from the end to beginning.
  2. Every time a space character is encountered i.e. " ", put the list of characters parsed till then in an ArrayList which can grow dynamically.
  3. Print the ArrayList in the reverse order which gives you the desired output.

Complexity: O(n) where n is the length of the String.

import java.io.IOException;
import java.util.ArrayList;

public class WordReverse {

    public static void main(String[] args) throws IOException {

        String inputStr = "Hello World";
        String reversed = "";
        ArrayList<String> alist = new ArrayList<String>();

        for (int i = inputStr.length() - 1; i >= 0; i--) {
            if (inputStr.charAt(i) != ' ') {
                reversed = reversed + inputStr.charAt(i);
            } else {
                alist.add(reversed);
                reversed = "";
            }
        }
        alist.add(reversed);
        String result = "";

        for (int i = alist.size() - 1; i >= 0; i--) {
            result = result + alist.get(i);
            result = result + " ";
        }
        System.out.println(result);
    }
}
酒中人 2024-09-01 05:38:53

TC - O(n) 和 SC - O(1) 的解决方案

public String reverseString(String str){
    String str = "Hello Wrold";
    int start = 0;

    for (int i = 0; i < str.length(); i++) {

        if (str.charAt(i) == ' ' || i == str.length() - 1) {

            int end = 0;

            if (i == str.length() - 1) {
                end = i;
            } else {
                end = i - 1;
            }

            str = swap(str, start, end);
            start = i + 1;
        }
    }
    System.out.println(str);
   }

 private static String swap(String str, int start, int end) {

    StringBuilder sb = new StringBuilder(str);

    while (start < end) {
        sb.setCharAt(start, str.charAt(end));
        sb.setCharAt(end, str.charAt(start));
        start++;
        end--;
    }
    return sb.toString();
}

Solution with TC - O(n) and SC - O(1)

public String reverseString(String str){
    String str = "Hello Wrold";
    int start = 0;

    for (int i = 0; i < str.length(); i++) {

        if (str.charAt(i) == ' ' || i == str.length() - 1) {

            int end = 0;

            if (i == str.length() - 1) {
                end = i;
            } else {
                end = i - 1;
            }

            str = swap(str, start, end);
            start = i + 1;
        }
    }
    System.out.println(str);
   }

 private static String swap(String str, int start, int end) {

    StringBuilder sb = new StringBuilder(str);

    while (start < end) {
        sb.setCharAt(start, str.charAt(end));
        sb.setCharAt(end, str.charAt(start));
        start++;
        end--;
    }
    return sb.toString();
}
巡山小妖精 2024-09-01 05:38:52
 package MujeebWorkspace.helps;
 // [email protected]

 public class Mujeeb {

     static String str= "This code is simple to reverse the word without changing positions";
     static String[] reverse = str.split(" ");

     public static void main(String [] args){  
         reverseMethod();
     }

     public static void reverseMethod(){
         for (int k=0; k<=reverse.length-1; k++) {
             String word =reverse[reverse.length-(reverse.length-k)];
             String subword = (word+" ");
             String [] splitsubword = subword.split("");

             for (int i=subword.length(); i>0; i--){
                 System.out.print(splitsubword[i]);  
             }
         }
     }
 }
 package MujeebWorkspace.helps;
 // [email protected]

 public class Mujeeb {

     static String str= "This code is simple to reverse the word without changing positions";
     static String[] reverse = str.split(" ");

     public static void main(String [] args){  
         reverseMethod();
     }

     public static void reverseMethod(){
         for (int k=0; k<=reverse.length-1; k++) {
             String word =reverse[reverse.length-(reverse.length-k)];
             String subword = (word+" ");
             String [] splitsubword = subword.split("");

             for (int i=subword.length(); i>0; i--){
                 System.out.print(splitsubword[i]);  
             }
         }
     }
 }
好多鱼好多余 2024-09-01 05:38:52
with and without api.

public class Reversal {
    public static void main(String s[]){
        String str= "hello world";
        reversal(str);
    }

    static void reversal(String str){
        String s[]=str.split(" ");
        StringBuilder noapi=new StringBuilder();
        StringBuilder api=new StringBuilder();
        for(String r:s){
            noapi.append(reversenoapi(r));
            api.append(reverseapi(r));
        }
        System.out.println(noapi.toString());
        System.out.println(api.toString());
    }

    static String reverseapi(String str){
        StringBuilder sb=new StringBuilder();
        sb.append(new StringBuilder(str).reverse().toString());
        sb.append(' ');
        return sb.toString();

    }

    static String reversenoapi(String str){
        StringBuilder sb=new StringBuilder();
        for(int i=str.length()-1;i>=0;i--){
            sb.append(str.charAt(i));
        }
        sb.append(" ");
        return sb.toString();
    }
}
with and without api.

public class Reversal {
    public static void main(String s[]){
        String str= "hello world";
        reversal(str);
    }

    static void reversal(String str){
        String s[]=str.split(" ");
        StringBuilder noapi=new StringBuilder();
        StringBuilder api=new StringBuilder();
        for(String r:s){
            noapi.append(reversenoapi(r));
            api.append(reverseapi(r));
        }
        System.out.println(noapi.toString());
        System.out.println(api.toString());
    }

    static String reverseapi(String str){
        StringBuilder sb=new StringBuilder();
        sb.append(new StringBuilder(str).reverse().toString());
        sb.append(' ');
        return sb.toString();

    }

    static String reversenoapi(String str){
        StringBuilder sb=new StringBuilder();
        for(int i=str.length()-1;i>=0;i--){
            sb.append(str.charAt(i));
        }
        sb.append(" ");
        return sb.toString();
    }
}
挽容 2024-09-01 05:38:51

使用 split() 函数并反转单个单词

    public String reverseSentence(String input)
      {
        String[] words = input.split(" ");
        StringBuilder builder = new StringBuilder();
        for (String s : words)
        {
            String rev = " ";
            for (int i = 0; i < s.length(); i++)
            {
                rev = s.charAt(i) + rev;
            }

            builder.append(rev);
        }

        return builder.toString().trim();
      }

使用 trim() 删除在新字符串末尾添加的额外空格

输出:

    This is my sentence        
    sihT si ym ecnetnes        

Use split() function and reverse individual words

    public String reverseSentence(String input)
      {
        String[] words = input.split(" ");
        StringBuilder builder = new StringBuilder();
        for (String s : words)
        {
            String rev = " ";
            for (int i = 0; i < s.length(); i++)
            {
                rev = s.charAt(i) + rev;
            }

            builder.append(rev);
        }

        return builder.toString().trim();
      }

Remove the extra space that is added at the end of the new String using trim()

Output:

    This is my sentence        
    sihT si ym ecnetnes        
伴我老 2024-09-01 05:38:51
public String reverse(String arg) {
    char[] s = arg.toCharArray();
    StringBuilder sb = new StringBuilder();
    boolean reverse = false;
    boolean isChar = false;
    int insertPos = 0;

    for (int i = 0; i < s.length; i++) {
        isChar = Character.isAlphabetic(s[i]);
        if (!reverse && isChar) {
            sb.append(s[i]);
            insertPos = i;
            reverse = true;
        } else if (reverse && isChar) {
            sb.insert(insertPos, s[i]);
        } else if (!reverse && !isChar) {
            sb.append(s[i]);
        } else if (reverse && !isChar) {
            reverse = false;
            sb.append(s[i]);
        }
    }

    return sb.toString();
}
public String reverse(String arg) {
    char[] s = arg.toCharArray();
    StringBuilder sb = new StringBuilder();
    boolean reverse = false;
    boolean isChar = false;
    int insertPos = 0;

    for (int i = 0; i < s.length; i++) {
        isChar = Character.isAlphabetic(s[i]);
        if (!reverse && isChar) {
            sb.append(s[i]);
            insertPos = i;
            reverse = true;
        } else if (reverse && isChar) {
            sb.insert(insertPos, s[i]);
        } else if (!reverse && !isChar) {
            sb.append(s[i]);
        } else if (reverse && !isChar) {
            reverse = false;
            sb.append(s[i]);
        }
    }

    return sb.toString();
}
无戏配角 2024-09-01 05:38:50
    String input = "Hello World!";

    String temp = "";
    String result = "";

    for (int i = 0; i <= input.length(); i++) {
        if (i != input.length() && input.charAt(i) != ' ') {
            temp = input.charAt(i) + temp;
        } else {
            result = temp + " " + result;
            temp = "";
        }
    }

    System.out.println("the result is: " + result);
    String input = "Hello World!";

    String temp = "";
    String result = "";

    for (int i = 0; i <= input.length(); i++) {
        if (i != input.length() && input.charAt(i) != ' ') {
            temp = input.charAt(i) + temp;
        } else {
            result = temp + " " + result;
            temp = "";
        }
    }

    System.out.println("the result is: " + result);
子栖 2024-09-01 05:38:50
class ReverseWordsInString{
    public static String reverse(String s1){
            int l = s1.length();
            if (l>1)
                    return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
            else
                    return(s1.substring(0));
    }
    public static void main(String[] args){
            String st = "Hello My World!";
            String r = "";
            for (String word : st.split(" "))
                    r += " "+ reverse(word);
            System.out.println("Reversed words in the given string: "+r.trim());
    }
}
class ReverseWordsInString{
    public static String reverse(String s1){
            int l = s1.length();
            if (l>1)
                    return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
            else
                    return(s1.substring(0));
    }
    public static void main(String[] args){
            String st = "Hello My World!";
            String r = "";
            for (String word : st.split(" "))
                    r += " "+ reverse(word);
            System.out.println("Reversed words in the given string: "+r.trim());
    }
}
_失温 2024-09-01 05:38:49

使用 split(),您只需更改您想要拆分的内容。

public static String reverseString(String str)
{
    String[] rstr;
    String result = "";
    int count = 0;
    rstr = str.split(" ");
    String words[] = new String[rstr.length];
    for(int i = rstr.length-1; i >= 0; i--)
    {
        words[count] = rstr[i];
        count++;
    }

    for(int j = 0; j <= words.length-1; j++)
    {
        result += words[j] + " ";
    }

    return result;


}

Using split(), you just have to change what you wish to split on.

public static String reverseString(String str)
{
    String[] rstr;
    String result = "";
    int count = 0;
    rstr = str.split(" ");
    String words[] = new String[rstr.length];
    for(int i = rstr.length-1; i >= 0; i--)
    {
        words[count] = rstr[i];
        count++;
    }

    for(int j = 0; j <= words.length-1; j++)
    {
        result += words[j] + " ";
    }

    return result;


}
浅浅淡淡 2024-09-01 05:38:48

我在解决这个问题时想出了这个答案。我尝试不使用嵌套 for 循环解决方案 O(N^2)。我强迫自己使用堆栈来娱乐:D

    public StringBuilder reverseWord(String input) {
        char separator = ' ';
        char[] chars = input.toCharArray();
        Stack<Character> stack = new Stack<Character>();
        StringBuilder sb = new StringBuilder(chars.length);


        for(int i = 0; i < chars.length; i++) {

            if(chars[i] != separator) { //letters
                stack.push(chars[i]);

                //if not last letter don't go any further
                if(i != chars.length - 1) { continue; }

            }

            while(!stack.isEmpty()) {
                sb.append(stack.pop());
            }
            sb.append(separator);

        }
        //remove the last separator
        sb.deleteCharAt(sb.length() - 1);
        return sb;
    }

I came up with this answer while working on the problem. I tried not to use nested for loop solution O(N^2). I kind of forced myself to use stack for fun :D

    public StringBuilder reverseWord(String input) {
        char separator = ' ';
        char[] chars = input.toCharArray();
        Stack<Character> stack = new Stack<Character>();
        StringBuilder sb = new StringBuilder(chars.length);


        for(int i = 0; i < chars.length; i++) {

            if(chars[i] != separator) { //letters
                stack.push(chars[i]);

                //if not last letter don't go any further
                if(i != chars.length - 1) { continue; }

            }

            while(!stack.isEmpty()) {
                sb.append(stack.pop());
            }
            sb.append(separator);

        }
        //remove the last separator
        sb.deleteCharAt(sb.length() - 1);
        return sb;
    }
梦中的蝴蝶 2024-09-01 05:38:48
public static void main(String[] args) {
        System.out.println(eatWord(new StringBuilder("Hello World This Is Tony's Code"), new StringBuilder(), new StringBuilder()));
    }
static StringBuilder eatWord(StringBuilder feed, StringBuilder swallowed, StringBuilder digested) {
    for (int i = 0, size = feed.length(); i <= size; i++) {
        if (feed.indexOf(" ") == 0 || feed.length() == 0) {
            digested.append(swallowed + " ");
            swallowed = new StringBuilder();
        } else {
            swallowed.insert(0, feed.charAt(0));
        }
        feed = (feed.length() > 0)  ? feed.delete(0, 1) : feed ;
    }
    return digested;
}

跑步:

olleH dlroW sihT sI s'ynoT edoC 
BUILD SUCCESSFUL (total time: 0 seconds)
public static void main(String[] args) {
        System.out.println(eatWord(new StringBuilder("Hello World This Is Tony's Code"), new StringBuilder(), new StringBuilder()));
    }
static StringBuilder eatWord(StringBuilder feed, StringBuilder swallowed, StringBuilder digested) {
    for (int i = 0, size = feed.length(); i <= size; i++) {
        if (feed.indexOf(" ") == 0 || feed.length() == 0) {
            digested.append(swallowed + " ");
            swallowed = new StringBuilder();
        } else {
            swallowed.insert(0, feed.charAt(0));
        }
        feed = (feed.length() > 0)  ? feed.delete(0, 1) : feed ;
    }
    return digested;
}

run:

olleH dlroW sihT sI s'ynoT edoC 
BUILD SUCCESSFUL (total time: 0 seconds)
心欲静而疯不止 2024-09-01 05:38:47

考虑到分隔符可以是多个空格/制表符,并且我们希望保留它们:

public static String reverse(String string)
{
    StringBuilder sb = new StringBuilder(string.length());
    StringBuilder wsb = new StringBuilder(string.length());
    for (int i = 0; i < string.length(); i++)
    {
        char c = string.charAt(i);
        if (c == '\t' || c == ' ')
        {
            if (wsb.length() > 0)
            {
                sb.append(wsb.reverse().toString());
                wsb = new StringBuilder(string.length() - sb.length());
            }
            sb.append(c);
        }
        else
        {
            wsb.append(c);
        }
    }
    if (wsb.length() > 0)
    {
        sb.append(wsb.reverse().toString());
    }
    return sb.toString();

}

Taking into account that the separator can be more than one space/tab and that we want to preserve them:

public static String reverse(String string)
{
    StringBuilder sb = new StringBuilder(string.length());
    StringBuilder wsb = new StringBuilder(string.length());
    for (int i = 0; i < string.length(); i++)
    {
        char c = string.charAt(i);
        if (c == '\t' || c == ' ')
        {
            if (wsb.length() > 0)
            {
                sb.append(wsb.reverse().toString());
                wsb = new StringBuilder(string.length() - sb.length());
            }
            sb.append(c);
        }
        else
        {
            wsb.append(c);
        }
    }
    if (wsb.length() > 0)
    {
        sb.append(wsb.reverse().toString());
    }
    return sb.toString();

}
夏日落 2024-09-01 05:38:47

这是一个接受字符串并将其反转的方法。

public String reverse ( String s ) {
            int length = s.length(), last = length - 1;
            char[] chars = s.toCharArray();
            for ( int i = 0; i < length/2; i++ ) {
                char c = chars[i];
                chars[i] = chars[last - i];
                chars[last - i] = c;
            }
            return new String(chars);
        }

首先,您需要将字符串拆分为这样的单词

String sample = "hello world";  
String[] words = sample.split(" ");  

Heres a method that takes a string and reverses it.

public String reverse ( String s ) {
            int length = s.length(), last = length - 1;
            char[] chars = s.toCharArray();
            for ( int i = 0; i < length/2; i++ ) {
                char c = chars[i];
                chars[i] = chars[last - i];
                chars[last - i] = c;
            }
            return new String(chars);
        }

First you need to split the string into words like this

String sample = "hello world";  
String[] words = sample.split(" ");  
離人涙 2024-09-01 05:38:46

我假设您可以只打印结果(您刚才说“输出应该是...”);-)

String str = "Hello World";
for (String word : str.split(" "))
    reverse(word);

void reverse(String s) {
    for (int idx = s.length() - 1; idx >= 0; idx--) 
        System.out.println(s.charAt(idx));
}

或者返回反转的字符串:

String str = "Hello World";
StringBuilder reversed = new StringBuilder();
for (String word : str.split(" ")) {
  reversed.append(reverse(word));
  reversed.append(' ');
}
System.out.println(reversed);

String reverse(String s) {
  StringBuilder b = new StringBuilder();
  for (int idx = s.length() - 1; idx >= 0; idx--)
      b.append(s.charAt(idx));
  return b.toString();
}

I'm assuming you could just print the results (you just said 'the output should be...') ;-)

String str = "Hello World";
for (String word : str.split(" "))
    reverse(word);

void reverse(String s) {
    for (int idx = s.length() - 1; idx >= 0; idx--) 
        System.out.println(s.charAt(idx));
}

Or returning the reversed String:

String str = "Hello World";
StringBuilder reversed = new StringBuilder();
for (String word : str.split(" ")) {
  reversed.append(reverse(word));
  reversed.append(' ');
}
System.out.println(reversed);

String reverse(String s) {
  StringBuilder b = new StringBuilder();
  for (int idx = s.length() - 1; idx >= 0; idx--)
      b.append(s.charAt(idx));
  return b.toString();
}
独自←快乐 2024-09-01 05:38:46

仅使用 substring() 和递归:

public String rev(String rest) {
    if (rest.equals(""))
        return "";
    return rev(rest.substring(1)) + rest.substring(0,1);
}

Using only substring() and recursion:

public String rev(String rest) {
    if (rest.equals(""))
        return "";
    return rev(rest.substring(1)) + rest.substring(0,1);
}
单身情人 2024-09-01 05:38:45

好吧,我是一名 C/C++ 人员,在面试中练习 java 让我知道是否可以更改或改进某些内容。以下允许多个空格和换行符。

第一个是使用 StringBuilder

public static String reverse(String str_words){
    StringBuilder sb_result = new StringBuilder(str_words.length());
    StringBuilder sb_tmp = new StringBuilder();
    char c_tmp;
    for(int i = 0; i < str_words.length(); i++){
        c_tmp = str_words.charAt(i);    
        if(c_tmp == ' ' || c_tmp == '\n'){
            if(sb_tmp.length() != 0){   
                sb_tmp.reverse();
                sb_result.append(sb_tmp);
                sb_tmp.setLength(0);
            }   
            sb_result.append(c_tmp);
        }else{
            sb_tmp.append(c_tmp);
        }
    } 
    if(sb_tmp.length() != 0){
        sb_tmp.reverse();
        sb_result.append(sb_tmp);
    }
    return sb_result.toString();
}

这个是使用 char[]。我觉得这样更有效率...

public static String reverse(String str_words){
    char[] c_array = str_words.toCharArray();
    int pos_start = 0;
    int pos_end;
    char c, c_tmp; 
    int i, j, rev_length;
    for(i = 0; i < c_array.length; i++){
        c = c_array[i];
        if( c == ' ' || c == '\n'){
            if(pos_start != i){ 
                pos_end = i-1;
                rev_length = (i-pos_start)/2;
                for(j = 0; j < rev_length; j++){
                    c_tmp = c_array[pos_start+j];
                    c_array[pos_start+j] = c_array[pos_end-j];
                    c_array[pos_end-j] = c_tmp;
                }
            }
            pos_start = i+1;
        }
    }
    //redundant, if only java had '\0' @ end of string
    if(pos_start != i){
        pos_end = i-1;
        rev_length = (i-pos_start)/2;
        for(j = 0; j < rev_length; j++){
            c_tmp = c_array[pos_start+j];
            c_array[pos_start+j] = c_array[pos_end-j];
            c_array[pos_end-j] = c_tmp;
        }
    }   
    return new String(c_array);
}

Well I'm a C/C++ guy, practicing java for interviews let me know if something can be changed or bettered. The following allows for multiple spaces and newlines.

First one is using StringBuilder

public static String reverse(String str_words){
    StringBuilder sb_result = new StringBuilder(str_words.length());
    StringBuilder sb_tmp = new StringBuilder();
    char c_tmp;
    for(int i = 0; i < str_words.length(); i++){
        c_tmp = str_words.charAt(i);    
        if(c_tmp == ' ' || c_tmp == '\n'){
            if(sb_tmp.length() != 0){   
                sb_tmp.reverse();
                sb_result.append(sb_tmp);
                sb_tmp.setLength(0);
            }   
            sb_result.append(c_tmp);
        }else{
            sb_tmp.append(c_tmp);
        }
    } 
    if(sb_tmp.length() != 0){
        sb_tmp.reverse();
        sb_result.append(sb_tmp);
    }
    return sb_result.toString();
}

This one is using char[]. I think its more efficient...

public static String reverse(String str_words){
    char[] c_array = str_words.toCharArray();
    int pos_start = 0;
    int pos_end;
    char c, c_tmp; 
    int i, j, rev_length;
    for(i = 0; i < c_array.length; i++){
        c = c_array[i];
        if( c == ' ' || c == '\n'){
            if(pos_start != i){ 
                pos_end = i-1;
                rev_length = (i-pos_start)/2;
                for(j = 0; j < rev_length; j++){
                    c_tmp = c_array[pos_start+j];
                    c_array[pos_start+j] = c_array[pos_end-j];
                    c_array[pos_end-j] = c_tmp;
                }
            }
            pos_start = i+1;
        }
    }
    //redundant, if only java had '\0' @ end of string
    if(pos_start != i){
        pos_end = i-1;
        rev_length = (i-pos_start)/2;
        for(j = 0; j < rev_length; j++){
            c_tmp = c_array[pos_start+j];
            c_array[pos_start+j] = c_array[pos_end-j];
            c_array[pos_end-j] = c_tmp;
        }
    }   
    return new String(c_array);
}
如此安好 2024-09-01 05:38:44

这里没有人考虑 unicode 字符。您需要使用 java.text.BreakIterator 来查找单词边界,然后在每个单词边界内使用另一个边界来枚举字符边界:

String helloWorld = "He\u0308llo World"; // Hëllo World
StringBuilder reverseStringBuilder = new StringBuilder(helloWorld.length());
BreakIterator wordBreakIterator = BreakIterator.getWordInstance();
wordBreakIterator.setText(helloWorld);

int wordStart = wordIterator.first();
int wordEnd = wordIterator.next();

while (wordEnd != BreakIterator.DONE) {
    String word = helloWorld.substring(wordStart,wordEnd);
    if (Character.isLetterOrDigit(word.charAt(0))) {
        // "Hello" or "World" in our example
        BreakIterator characterBreakIterator = BreakIterator.getCharacterInstance();
        characterBreakIterator.setText(word);
        int characterEnd = characterBreakIterator.last();
        int characterStart = characterBreakIterator.previous();
        while (characterStart != BreakIterator.DONE) {
            reverseStringBuilder.append(word.substring(characterStart, characterEnd));

            characterEnd = characterStart;
            characterStart = characterBreakIterator.previous();
        }
    } else {
        // " " in our example
        reverseStringBuilder.append(word);
    }
    wordStart = wordEnd;
    wordEnd = wordIterator.next();
}

String dlroWolleh = reverseStringBuilder.toString(); // "dlroW ollëH"

使用上面的简单方法将移动变音符号 \u0308String 时,code> 位于第一个 l 之上。您希望它保持在 e 之上。

No one here is considering unicode characters. You need to use java.text.BreakIterator to find word boundaries and then use another one within each word boundary to enumerate character boundaries:

String helloWorld = "He\u0308llo World"; // Hëllo World
StringBuilder reverseStringBuilder = new StringBuilder(helloWorld.length());
BreakIterator wordBreakIterator = BreakIterator.getWordInstance();
wordBreakIterator.setText(helloWorld);

int wordStart = wordIterator.first();
int wordEnd = wordIterator.next();

while (wordEnd != BreakIterator.DONE) {
    String word = helloWorld.substring(wordStart,wordEnd);
    if (Character.isLetterOrDigit(word.charAt(0))) {
        // "Hello" or "World" in our example
        BreakIterator characterBreakIterator = BreakIterator.getCharacterInstance();
        characterBreakIterator.setText(word);
        int characterEnd = characterBreakIterator.last();
        int characterStart = characterBreakIterator.previous();
        while (characterStart != BreakIterator.DONE) {
            reverseStringBuilder.append(word.substring(characterStart, characterEnd));

            characterEnd = characterStart;
            characterStart = characterBreakIterator.previous();
        }
    } else {
        // " " in our example
        reverseStringBuilder.append(word);
    }
    wordStart = wordEnd;
    wordEnd = wordIterator.next();
}

String dlroWolleh = reverseStringBuilder.toString(); // "dlroW ollëH"

Using naive methods above will shift the diacritic character \u0308 above the first l when you reverse the String. You want it to stay above the e.

小兔几 2024-09-01 05:38:43

这是最简单的解决方案,甚至不使用任何循环。

public class olleHdlroW {
    static String reverse(String in, String out) {
        return (in.isEmpty()) ? out :
            (in.charAt(0) == ' ')
            ? out + ' ' + reverse(in.substring(1), "")
            : reverse(in.substring(1), in.charAt(0) + out);
    }
    public static void main(String args[]) {
        System.out.println(reverse("Hello World", ""));
    }
}

即使这是作业,也可以随意复制并作为您自己的作业提交。你要么获得额外的学分(如果你能解释它是如何工作的),要么因抄袭而被抓(如果你不能)。

Here's the simplest solution that doesn't even use any loops.

public class olleHdlroW {
    static String reverse(String in, String out) {
        return (in.isEmpty()) ? out :
            (in.charAt(0) == ' ')
            ? out + ' ' + reverse(in.substring(1), "")
            : reverse(in.substring(1), in.charAt(0) + out);
    }
    public static void main(String args[]) {
        System.out.println(reverse("Hello World", ""));
    }
}

Even if this is homework, feel free to copy it and submit it as your own. You'll either get an extra credit (if you can explain how it works) or get caught for plagiarism (if you can't).

海的爱人是光 2024-09-01 05:38:42

分割为单词数组后,您需要对每个单词执行此操作。

public String reverse(String word) {
    char[] chs = word.toCharArray();

    int i=0, j=chs.length-1;
    while (i < j) {
        // swap chs[i] and chs[j]
        char t = chs[i];
        chs[i] = chs[j];
        chs[j] = t;
       i++; j--;
    }
    return String.valueOf(chs);
}

You need to do this on each word after you split into an array of words.

public String reverse(String word) {
    char[] chs = word.toCharArray();

    int i=0, j=chs.length-1;
    while (i < j) {
        // swap chs[i] and chs[j]
        char t = chs[i];
        chs[i] = chs[j];
        chs[j] = t;
       i++; j--;
    }
    return String.valueOf(chs);
}
神回复 2024-09-01 05:38:41

了解您的图书馆;-)

import org.apache.commons.lang.StringUtils;

String reverseWords(String sentence) {
    return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' ');
}

Know your libraries ;-)

import org.apache.commons.lang.StringUtils;

String reverseWords(String sentence) {
    return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' ');
}
り繁华旳梦境 2024-09-01 05:38:40

这应该可以解决问题。这将迭代源字符串中的每个单词,并使用 StringBuilder内置的reverse()方法,并输出反转的单词。

String source = "Hello World";

for (String part : source.split(" ")) {
    System.out.print(new StringBuilder(part).reverse().toString());
    System.out.print(" ");
}

输出:

olleH dlroW 

注释:评论者正确地指出了一些我认为应该在这里提到的事情。此示例将在结果末尾附加一个额外的空格。它还假设您的单词之间用一个空格分隔,并且您的句子不包含标点符号。

This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder's built-in reverse() method, and output the reversed word.

String source = "Hello World";

for (String part : source.split(" ")) {
    System.out.print(new StringBuilder(part).reverse().toString());
    System.out.print(" ");
}

Output:

olleH dlroW 

Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文