在Java中反转string

我把"Hello World"保存在名为hi的Stringvariables中。

我需要打印它,但相反。

我该怎么做? 我知道有一种已经embedded到Java中的function。

相关: 用Java反转“Hello World”string的每个单词

你可以使用这个:

 new StringBuilder(hi).reverse().toString() 

或者,对于早于JDK 1.5的版本,请使用java.util.StringBuffer而不是StringBuilder – 它们具有相同的API。 感谢评论员指出,现在StringBuilder是首选。

对于不允许StringBuilderStringBuffer 在线裁判问题 ,您可以使用char[] ,如下所示:

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

我正在使用以下两种方法:

通过CHARACTERS反向string:

 public static void main(String[] args) { // Using treditonal 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反向string:

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

这是一个使用recursion的例子:

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

看看StringBuffer下的Java 6 API

 String s = "sample"; String result = new StringBuffer(s).reverse().toString(); 

这是一个低级解决scheme:

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

我尝试了,只是为了好玩,通过使用堆栈。 在这里我的代码:

 public String reverseString(String s) { Stack<Character> stack = new Stack<Character>(); 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(); } 

由于下面的方法(使用异或 )来反转string没有列出,所以我附上了这个方法来反转string。

algorithm基于:

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

输出:

keetarp

正如其他人指出的,首选的方法是使用:

new StringBuilder(hi).reverse().toString()

但是如果你想自己实现这个,恐怕其余的答案都有缺陷。

原因是String代表根据可变长度编码UTF-16编码在char[]数组中的Unicode点的列表。

这意味着一些代码点使用数组中的单个元素(一个代码单元),但其他代码使用其中的两个,所以可能有必须被视为单个单元的字符对(连续的“高”和“低”替代)

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

在最小代码行中非常简单

 public class ReverseString { public static void main(String[] args) { String s1 = "neelendra"; for(int i=s1.length()-1;i>=0;i--) { System.out.print(s1.charAt(i)); } } } 

这为我做了诡计

 public static void main(String[] args) { String text = "abcdefghijklmnopqrstuvwxyz"; for (int i = (text.length() - 1); i >= 0; i--) { System.out.print(text.charAt(i)); } } 
 System.out.print("Please enter your name: "); String name = keyboard.nextLine(); String reverse = new StringBuffer(name).reverse().toString(); String rev = reverse.toLowerCase(); System.out.println(rev); 

我用这种方法把名字倒转成小写。

  public String reverse(String s) { String reversedString = ""; for(int i=s.length(); i>0; i--) { reversedString += s.charAt(i-1); } return reversedString; } 

一个反转String自然方法是使用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); } } 

以上所有的解决scheme是太好了,但在这里我正在使用recursion编程反向string。

这对于谁在寻找做反向string的recursion方式是有帮助的。

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

1.使用字符数组:

 public String reverseSting(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 reverseSting(String inputString) { StringBuilder stringBuilder = new StringBuilder(inputString); stringBuilder = stringBuilder.reverse(); return stringBuilder.toString(); } 

要么

 return new StringBuilder(inputString).reverse().toString(); 

通过字符反转string:

 public class Main { public static void main(String[] args) { String str1 = "whatever string something"; StringBuffer str1buff = new StringBuffer(str1); String str1rev = str1buff.reverse().toString(); System.out.println(str1rev); } } 

通过Word反转string:

公共课Main {

 public static void main(String[] args) { String str1 = "reverse this string"; Stack<Object> stack = new Stack<>(); StringTokenizer strTok = new StringTokenizer(str1); while(strTok.hasMoreTokens()){ stack.push(strTok.nextElement()); } StringBuffer str1rev = new StringBuffer(); while(!stack.empty()){ str1rev.append(stack.pop()); str1rev.append(" "); } System.out.println(str1rev); } } 

只是为了好玩.. :)algorithm(str,len)

char reversedStr [] = new reversedStr [len]

  1. 遍历我从0到len / 2
  2. reversedStr [I] = STR [LEN-1-I]
  3. reversedStr [LEN-1 = I] = STR [1]

退回;

时间复杂度: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); } } 
 import java.util.Scanner; public class StringReverseExample { public static void main(String[] args) { String str,rev; Scanner in = new Scanner(System.in); System.out.print("Enter the string : "); str = in.nextLine(); rev = new StringBuffer(str).reverse().toString(); System.out.println("\nString before reverse:"+str); System.out.println("String after reverse:"+rev); } } /* Output : Enter the string : satyam String before reverse:satyam String after reverse:maytas */ 
 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); } } 

如果你想使用一个简单的循环!

它得到你input的值并将其返回;)

 public static String reverse (String a){ char[] rarray = a.toCharArray(); String finalvalue = ""; for (int i = 0; i < rarray.length; i++) { finalvalue += rarray[rarray.length - 1 - i]; } return finalvalue; 

}

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); } 
 StringBuilder s = new StringBuilder("racecar"); for (int i = 0, j = s.length() - 1; i < (s.length()/2); i++, j--) { char temp = s.charAt(i); s.setCharAt(i, s.charAt(j)); s.setCharAt(j, temp); } System.out.println(s.toString()); 

你也可以试试这个:

 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 static void main(String[] args) { String str = "Prashant"; int len = str.length(); char[] c = new char[len]; for (int j = len - 1, i = 0; j >= 0; j--, i++) { c[i] = str.charAt(j); } str = String.copyValueOf(c); System.out.println(str); }