我有“Hello World”保存在一个名为hi的字符串变量中。
我需要打印出来,但要颠倒过来。
我该怎么做呢?我知道Java中已经内置了这样一个函数。
相关:用Java反向“Hello World”字符串的每一个单词
我有“Hello World”保存在一个名为hi的字符串变量中。
我需要打印出来,但要颠倒过来。
我该怎么做呢?我知道Java中已经内置了这样一个函数。
相关:用Java反向“Hello World”字符串的每一个单词
当前回答
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 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);
}
字符串家族的字符序列(或)
String testString = "Yashwanth@777"; // ~1 1⁄4→D800₁₆«2²⁰
使用Java 8流API
首先使用CharSequence.chars()方法将String转换为流,然后使用IntStream方法。范围来生成连续的数字流。然后我们将这个stream序列映射到String中。
public static String reverseString_Stream(String str) {
IntStream cahrStream = str.chars();
final int[] array = cahrStream.map( x -> x ).toArray();
int from = 0, upTo = array.length;
IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
.mapToObj( reverseMapper ) // array[ lastElement ]
.collect(Collectors.joining()) // Joining stream of elements together into a String.
.toString(); // This object (which is already a string!) is itself returned.
System.out.println("Reverse Stream as String : "+ reverseString);
return reverseString;
}
使用传统的for循环
如果您想反转字符串,那么我们需要遵循以下步骤。
将字符串转换为字符数组。 以倒序遍历数组,将每个字符附加到临时字符串变量,直到最后一个字符。
public static String reverseString( String reverse ) {
if( reverse != null && reverse != "" && reverse.length() > 0 ) {
char[] arr = reverse.toCharArray();
String temp = "";
for( int i = arr.length-1; i >= 0; i-- ) {
temp += arr[i];
}
System.out.println("Reverse String : "+ temp);
}
return null;
}
简单的方法使用反向方法提供的StringBuffer或StringBuilder类
StringBuilder和StringBuffer是可变的字符序列。这意味着可以改变这些对象的值。
StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );
StringBuffer具有与StringBuilder相同的方法,但是StringBuffer中的每个方法都是同步的,因此它是线程安全的。
看一下StringBuffer下的Java 6 API
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
对于不允许StringBuilder或StringBuffer的Online Judges问题,可以使用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 class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}