java 反转字符串数组中每个单词的Java方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27436643/
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-11-02 11:48:24  来源:igfitidea点击:

Java method to reverse every word in an array of strings

javaarraysstringreverse

提问by Justin

I'm trying to make a method that will take an array of strings and return an array with all the words in reverse order but my code is not working.

我正在尝试创建一个方法,该方法将采用一个字符串数组并以相反的顺序返回一个包含所有单词的数组,但我的代码不起作用。

When I run it i get "[Ljava.lang.String;@74122d9c"

当我运行它时,我得到“[Ljava.lang.String;@74122d9c”

Test case: String[]words={"Monday","Tuesday","Wednesday"}; -->{"yadnoM","yadsueT","yadsendeW"};

测试用例:String[]words={"Monday","Tuesday","Wednesday"}; -->{"yadnoM","yadsueT","yadsendeW"};

public String[] reverseString(String[] words)
{
    String[] t=new String[words.length];

    for(int i=0;i<words.length;i++)
    {
        for(int j=words[i].length()-1;j>=0;j--)
        {
            t[i]+=words[i].substring(j,j+1);
        }
    }
    return t;
}

回答by Scary Wombat

try using StringBuilder.reverse

尝试使用 StringBuilder.reverse

public String[] reverseString(String[] words) {
        String[] t = new String[words.length];
        for (int i = 0; i < words.length; i++) {
            t[i]= new StringBuilder(words[i]).reverse().toString();
        }
        return t;
    }

Update

更新

The fact that you are getting When I run it i get "[Ljava.lang.String;@74122d9c"is beccase you are printing the whole String array as one [Ljava.lang.Stringmeans String array. You will need to iterate over the array to print out the Strings one-by-one

你得到的事实When I run it i get "[Ljava.lang.String;@74122d9c"是因为你正在打印整个 String 数组,因为它[Ljava.lang.String意味着 String 数组。您将需要遍历数组以一一打印出字符串

回答by Panther

You can transform your string into StringBuilder and it had reverse method. And its always better to use foreach rather than for, until there is actual need.

您可以将字符串转换为 StringBuilder 并且它具有反向方法。并且在实际需要之前使用 foreach 而不是 for 总是更好。

public String[] reverseString(String[] words) {
    String[] t = new String[words.length];
    for (String wordTemp : words) {
      StringBuilder sb = new StringBuilder(wordTemp);
      t[i] = sb.reverse().toString();   
    }
    return t;
}

Alternate approach :-

替代方法:-

public  String[]  reverseString(String[] words)
{
    String[] t=new String[words.length];

    for(int i=0;i<words.length;i++)
    {   
        //added for setting elemennt as emptyString instead of null
        t[i] = "";
        for(int j=words[i].length()-1;j>=0;j--)
        {
            t[i]+=words[i].substring(j,j+1);
        }
    }

    //using loop
    for(int i=0;i<words.length;i++)
    {
         System.out.println(t[i]);
    }
    //using Arrays Method
    System.out.println(Arrays.toString(t));
    return t;
}

回答by Shadow

When I run your code, I didn't get the same error that you posted, but I did notice that nullwas at the end of each reversed word.

当我运行您的代码时,我没有收到您发布的相同错误,但我确实注意到它null位于每个反向单词的末尾。

nullyadnoM
nullyadseuT
nullyadsendeW

Which is beacuse when you create a new string array, all it's values default to null:

这是因为当你创建一个新的字符串数组时,它的所有值默认为 null:

String[] t = new String[words.length];

The easiest way to fix it is to set it's value to an empty string, before you start adding to it:

修复它的最简单方法是在开始添加之前将其值设置为空字符串:

public static String[] reverseString(String[] words)
{
    String[] t = new String[words.length];

    for (int i = 0; i < words.length; i++)
    {
        t[i] = "";
        for (int j = words[i].length() - 1; j >= 0; j--)
            t[i] += words[i].charAt(j);
    }
    return t;
}

I have tested this code, and it works perfectly fine for me.

我已经测试了这段代码,它对我来说非常好。

To output the array, instead of using

输出数组,而不是使用

System.out.println(words);

use the following:

使用以下内容:

System.out.println(Arrays.toString(words));

This will give you the output:

这将为您提供输出:

[yadnoM, yadseuT, yadsendeW]

回答by Ravi Durairaj

Below Code is working fine with the help Stringbuilder reverse function.

下面的代码在帮助 Stringbuilder 反向功能下工作正常。

public class Example {

公共类示例{

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String[] irreverseStr = {"Monday","Tuesday","Wendesday","Thursday","Friday","Saturday","Sunday"};           
    String[] reverseStr = new Example().getReverseArray(irreverseStr);

    for(int j = 0; j < reverseStr.length; j++){
        System.out.println(reverseStr[j]);
    }           
}

public String[] getReverseArray(String[] str){      
    String [] reversestr = new String[str.length];      
    for(int i=0;i<reversestr.length;i++){
        reversestr[i] = new StringBuilder(str[i]).reverse().toString();
    }       
    return reversestr;
}

}

}

回答by Shiva

Well, to return an array with all the words in reverse order try code below,

好吧,要以相反的顺序返回一个包含所有单词的数组,请尝试下面的代码,

import java.util.Arrays;

public class ArrayUtilsReverse 
{
   public static void main(String[] args) 
   {
      String strArray[] = { "Monday","Tuesday","Wednesday" };
      System.out.println("Print string array in reverse order java : " + Arrays.toString(strArray));

      for(int a = 0; a < strArray.length / 2; a++)
      {
         String str = strArray[a];
         strArray[a] = strArray[strArray.length - a - 1];
         strArray[strArray.length - a - 1] = str; 
      }

      System.out.println("Reversed array : ");
      for(int a = 0; a < strArray.length; a++)
      {
         System.out.println(strArray[a]);
      }
   }
}

Output:

输出:

Print string array in reverse order java : [Monday, Tuesday, Wednesday]
Reversed array : 
Wednesday
Tuesday
Monday

For more examples on reverse string array in java refer thisresource.

有关 Java 中反向字符串数组的更多示例,请参阅资源。

回答by Ankur Singhal

 public static void main(String[] args) {
        String[] words = { "Monday", "Tuesday", "Wednesday" };
        for (int i = 0 ; i < words.length ; i++) {
            words[i] = Reverse(words[i]);
        }
        for (int i = 0 ; i < words.length ; i++) {
            System.out.println(words[i]);
        }

    }

    private static String Reverse(String str) {
        StringBuilder result = new StringBuilder();
        StringTokenizer st = new StringTokenizer(str, "");
        while (st.hasMoreTokens()) {
            StringBuilder thisToken = new StringBuilder(st.nextToken());
            result.append(thisToken.reverse() + " ");
        }
        return result.toString();
    }

Output

输出

yadnoM 
yadseuT 
yadsendeW 

Also you can use org.apache.commons.lang3.StringUtils;, just to reduce your effort/shorten the code

你也可以使用org.apache.commons.lang3.StringUtils;,只是为了减少你的工作/缩短代码

private static String Reverse(String str) {
        return StringUtils.reverse(str);
    }

回答by Arun Xavier

public static String[] reverseString(String[] words) {
    String[] t = new String[words.length];
    for (int i = 0; i < words.length; i++) {
        t[i]=new StringBuffer(words[i]).reverse().toString();

    }
    return t;
}

try StringBuffer's reverse method

试试 StringBuffer 的 reverse 方法