我"Hello World"保存在一个名为的String变量中hi。
我需要打印,但是要反转。
我怎样才能做到这一点?我知道Java中已经内置了某种功能。
我"Hello World"保存在一个名为的String变量中hi。
我需要打印,但是要反转。
我怎样才能做到这一点?我知道Java中已经内置了某种功能。
Answers:
您可以使用此:
new StringBuilder(hi).reverse().toString()
或者,对于JDK 1.5之前的版本,请使用java.util.StringBuffer代替StringBuilder-它们具有相同的API。感谢评论员指出,StringBuilder在当今没有并发问题的情况下,这是首选。
StringBuilder并发的方案,不必担心(我认为这就是他的意思)。
                    String hi = "Hello World";。所以我觉得在你的答案应该不被周围的任何双引号hi。我的意思是应该这样new StringBuilder(hi).reverse().toString()
                    对于不允许或的在线法官问题,您可以使用以下方法就地解决:StringBuilderStringBufferchar[]
public static String reverse(String input){
    char[] in = input.toCharArray();
    int begin=0;
    int end=in.length-1;
    char temp;
    while(end>begin){
        temp = in[begin];
        in[begin]=in[end];
        in[end] = temp;
        end--;
        begin++;
    }
    return new String(in);
}
              public static String reverseIt(String source) {
    int i, len = source.length();
    StringBuilder dest = new StringBuilder(len);
    for (i = (len - 1); i >= 0; i--){
        dest.append(source.charAt(i));
    }
    return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
              我通过以下两种方式来做到这一点:
按字符反向字符串:
public static void main(String[] args) {
    // Using traditional approach
    String result="";
    for(int i=string.length()-1; i>=0; i--) {
        result = result + string.charAt(i);
    }
    System.out.println(result);
    // Using StringBuffer class
    StringBuffer buffer = new StringBuffer(string);
    System.out.println(buffer.reverse());    
}
用WORDS反向字符串:
public static void reverseStringByWords(String string) {
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = string.split(" ");
    for (int j = words.length-1; j >= 0; j--) {
        stringBuilder.append(words[j]).append(' ');
    }
    System.out.println("Reverse words: " + stringBuilder);
}
              看看StringBuffer下的Java 6 API
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
              reverse()和toString()),因此差异可能不会是可测量的。
                    这是使用递归的示例:
public void reverseString() {
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
    if(index == 0){
        return stringToReverse.charAt(0) + "";
    }
    char letter = stringToReverse.charAt(index);
    return letter + reverse(stringToReverse, index-1);
}
              这是一个底层解决方案:
import java.util.Scanner;
public class class1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String inpStr = in.nextLine();
        System.out.println("Original String :" + inpStr);
        char temp;
        char[] arr = inpStr.toCharArray();
        int len = arr.length;
        for(int i=0; i<(inpStr.length())/2; i++,len--){
            temp = arr[i];
            arr[i] = arr[len-1];
            arr[len-1] = temp;
        }
        System.out.println("Reverse String :" + String.valueOf(arr));
    }
}
              我尝试使用Stack只是为了好玩。这是我的代码:
public String reverseString(String s) {
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        stack.push(s.charAt(i));
    }
    while (!stack.empty()) {
        sb.append(stack.pop());
    }
    return sb.toString();
}
              由于未列出以下方法(使用XOR)来反转字符串,因此我附加了此方法来反转字符串。
该算法基于:
1.(A XOR B)XOR B = A
2.(A XOR B)XOR A = B
程式码片段:
public class ReverseUsingXOR {
    public static void main(String[] args) {
        String str = "prateek";
        reverseUsingXOR(str.toCharArray());
    }   
    /*Example:
     * str= prateek;
     * str[low]=p;
     * str[high]=k;
     * str[low]=p^k;
     * str[high]=(p^k)^k =p;
     * str[low]=(p^k)^p=k;
     * 
     * */
    public static void reverseUsingXOR(char[] str) {
        int low = 0;
        int high = str.length - 1;
        while (low < high) {
            str[low] = (char) (str[low] ^ str[high]);
            str[high] = (char) (str[low] ^ str[high]);   
            str[low] = (char) (str[low] ^ str[high]);
            low++;
            high--;
        }
        //display reversed string
        for (int i = 0; i < str.length; i++) {
            System.out.print(str[i]);
        }
    }
}
输出:
基塔普
正如其他人指出的,首选方式是使用:
new StringBuilder(hi).reverse().toString()
但是,如果您想自己实现这一点,恐怕其余的回答都存在缺陷。
原因是String表示一个Unicode点列表,char[]根据可变长度编码将其编码为数组:UTF-16。
这意味着某些代码点使用数组的单个元素(一个代码单元),而其他代码点使用其中的两个,因此可能必须将成对的字符视为一个单元(连续的“高”和“低”替代) 。
public static String reverseString(String s) {
    char[] chars = new char[s.length()];
    boolean twoCharCodepoint = false;
    for (int i = 0; i < s.length(); i++) {
        chars[s.length() - 1 - i] = s.charAt(i);
        if (twoCharCodepoint) {
            swap(chars, s.length() - 1 - i, s.length() - i);
        }
        twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
    }
    return new String(chars);
}
private static void swap(char[] array, int i, int j) {
    char temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
    StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
    sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
    sb.append(".");
    fos.write(sb.toString().getBytes("UTF-16"));
    fos.write("\n".getBytes("UTF-16"));
    fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
              1.使用字符数组:
public String reverseString(String inputString) {
    char[] inputStringArray = inputString.toCharArray();
    String reverseString = "";
    for (int i = inputStringArray.length - 1; i >= 0; i--) {
        reverseString += inputStringArray[i];
    }
    return reverseString;
}
2.使用StringBuilder:
public String reverseString(String inputString) {
    StringBuilder stringBuilder = new StringBuilder(inputString);
    stringBuilder = stringBuilder.reverse();
    return stringBuilder.toString();
}
要么
return new StringBuilder(inputString).reverse().toString();
                  public String reverse(String s) {
        String reversedString = "";
        for(int i=s.length(); i>0; i--) {
            reversedString += s.charAt(i-1);
        }   
        return reversedString;
    }
              反转a的一种自然方法String是使用a StringTokenizer和堆栈。Stack是一个实现易于使用的后进先出(LIFO)对象堆栈的类。
String s = "Hello My name is Sufiyan";
向前放入堆栈
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
     myStack.push(st.nextToken());
}
向后打印堆栈
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
  System.out.print(myStack.pop());
  System.out.print(' ');
}
System.out.println('"');
              public class Test {
public static void main(String args[]) {
   StringBuffer buffer = new StringBuffer("Game Plan");
   buffer.reverse();
   System.out.println(buffer);
 }  
}
              以上所有解决方案都很好,但是在这里我使用递归编程制作反向字符串。
这对于谁正在寻找执行反向字符串的递归方式很有帮助。
public class ReversString {
public static void main(String args[]) {
    char s[] = "Dhiral Pandya".toCharArray();
    String r = new String(reverse(0, s));
    System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
    if (source.length / 2 == i) {
        return source;
    }
    char t = source[i];
    source[i] = source[source.length - 1 - i];
    source[source.length - 1 - i] = t;
    i++;
    return reverse(i, source);
}
}
              我们可以使用split()分割字符串,然后使用反向循环并添加字符。
class test
{
  public static void main(String args[]) 
  {
      String str = "world";
      String[] split= str.split("");
      String revers = "";
      for (int i = split.length-1; i>=0; i--)
      {
        revers += split[i];
      }
      System.out.printf("%s", revers);
   }  
}
 //output : dlrow
public String reverseWords(String s){
    String reversedWords = "";
    if(s.length()<=0) {
        return reversedWords;
    }else if(s.length() == 1){
        if(s == " "){
            return "";
        }
        return s;
    }
    char arr[] = s.toCharArray();
    int j = arr.length-1;
    while(j >= 0 ){
        if( arr[j] == ' '){
            reversedWords+=arr[j];
        }else{
            String temp="";
            while(j>=0 && arr[j] != ' '){
                temp+=arr[j];
                j--;
            }
            j++;
            temp = reverseWord(temp);
            reversedWords+=temp;
        }
        j--;
    }
    String[] chk = reversedWords.split(" ");
    if(chk == null || chk.length == 0){
        return "";
    }
    return reversedWords;
}
public String reverseWord(String s){
    char[] arr = s.toCharArray();
    for(int i=0,j=arr.length-1;i<=j;i++,j--){
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    return String.valueOf(arr);
}
              您也可以尝试以下操作:
public class StringReverse {
    public static void main(String[] args) {
        String str = "Dogs hates cats";
        StringBuffer sb = new StringBuffer(str);
        System.out.println(sb.reverse());
    }
}
              public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 try{
  String str=br.readLine();
  char[] charArray=str.toCharArray();
  for(int i=charArray.length-1; i>=0; i--){
   System.out.println(charArray[i]);
  }
  }
   catch(IOException ex){
  }
              递归:
 public String stringReverse(String string) {
    if (string == null || string.length() == 0) {
        return string;
    }
    return stringReverse(string.substring(1)) + string.charAt(0);
 }
              纯娱乐..:)
Algorithm (str,len)
char reversedStr[] =new reversedStr[len]
将i从0遍历到len / 2,然后
reversedStr[i]=str[len-1-i]  
reversedStr[len-1=i]=str[i]
return reversedStr;
时间复杂度:O(n)
空间复杂度:O(n)
public class Reverse {
    static char reversedStr[];
    public static void main(String[] args) {
        System.out.println(reversestr("jatin"));
    }
    private static String reversestr(String str) {
        int strlen = str.length();
        reversedStr = new char[strlen];
        for (int i = 0; i <= strlen / 2; i++) {
            reversedStr[i] = str.charAt(strlen - 1 - i);
            reversedStr[strlen - 1 - i] = str.charAt(i);
        }
        return new String(reversedStr);
    }
}
              public static String revString(String str){
    char[] revCharArr = str.toCharArray();
    for (int i=0; i< str.length()/2; i++){
        char f = revCharArr[i];
        char l = revCharArr[str.length()-i-1];
        revCharArr[i] = l;
        revCharArr[str.length()-i-1] = f;
    }
    String revStr = new String(revCharArr);
    return revStr;
}
                  public static void reverseString(String s){
        System.out.println("---------");
        for(int i=s.length()-1; i>=0;i--){
            System.out.print(s.charAt(i));    
        }
        System.out.println(); 
    }
                  //Solution #1 -- Using array and charAt()
    String name = "reverse"; //String to reverse
    Character[] nameChar =  new Character[name.length()]; // Declaring a character array with length as length of the String which you want to reverse.
    for(int i=0;i<name.length();i++)// this will loop you through the String
    nameChar[i]=name.charAt(name.length()-1-i);// Using built in charAt() we can fetch the character at a given index. 
    for(char nam:nameChar)// Just to print the above nameChar character Array using an enhanced for loop
    System.out.print(nam);
    //Solution #2 - Using StringBuffer and reverse ().
    StringBuffer reverseString = new StringBuffer("reverse");
    System.out.println(reverseString.reverse()); //reverse () Causes the character sequence to be replaced by the reverse of the sequence.
              package logicprogram;
import java.io.*;
public class Strinrevers {
public static void main(String args[])throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("enter data");
    String data=br.readLine();
    System.out.println(data);
    String str="";
    char cha[]=data.toCharArray();
    int l=data.length();
    int k=l-1;
    System.out.println(l);
    for(int i=0;k>=i;k--)
    {
        str+=cha[k];
    }
    //String text=String.valueOf(ch);
    System.out.println(str);
}
}
              import java.util.Scanner;
public class Test {
    public static void main(String[] args){
        Scanner input = new Scanner (System.in);
        String word = input.next();
        String reverse = "";
        for(int i=word.length()-1; i>=0; i--)
            reverse += word.charAt(i);
        System.out.println(reverse);        
    }
}
如果要使用简单的for循环!