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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2441501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:41:35  来源:igfitidea点击:

Reverse each individual word of "Hello World" string with Java

javastringreverse

提问by Vicheanak

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

我要扭转各个人在Java中的String(不是整个字符串,只是每个人的字)的字。

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

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

采纳答案by William Brendel

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.

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

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.

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

回答by fastcodejava

You need to do this on each word after you splitinto an arrayof words.

在你split进入一个词之后,你需要对每个词都这样做array

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

回答by Zaki

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

回答by Sawyer

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)

回答by polygenelubricants

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).

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

回答by JRL

Know your libraries ;-)

了解你的图书馆 ;-)

import org.apache.commons.lang.StringUtils;

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

回答by Mikel

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

}

回答by sysoutnull

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

回答by Baracs

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.

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

First one is using StringBuilder

第一个是使用 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...

这是使用 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 '
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;


}
' @ 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); }

回答by ewein

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

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

##代码##