我有“Hello World”保存在一个名为hi的字符串变量中。
我需要打印出来,但要颠倒过来。
我该怎么做呢?我知道Java中已经内置了这样一个函数。
相关:用Java反向“Hello World”字符串的每一个单词
我有“Hello World”保存在一个名为hi的字符串变量中。
我需要打印出来,但要颠倒过来。
我该怎么做呢?我知道Java中已经内置了这样一个函数。
相关:用Java反向“Hello World”字符串的每一个单词
当前回答
正如其他人指出的那样,首选的方法是使用:
new StringBuilder(hi).reverse().toString()
但如果你想自己实现这个,恐怕其余的回答都有缺陷。
原因是String表示Unicode点的列表,根据变长编码:UTF-16编码在char[]数组中。
这意味着一些代码点使用数组的单个元素(一个代码单元),但其他代码点使用其中的两个,因此可能会有一对字符必须被视为单个单元(连续的“高”和“低”代理)。
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"));
}
其他回答
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);
我使用这种方法将名称反向转换为小写。
反转字符串有很多种方法。
1. 将字符串转换为字节:getBytes()方法用于将输入字符串转换为字节[]。
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
String input = "GeeksforGeeks";
byte [] strAsByteArray = input.getBytes();
byte [] result = new byte [strAsByteArray.length];
for (int i = 0; i<strAsByteArray.length; i++)
result[i] =
strAsByteArray[strAsByteArray.length-i-1];
System.out.println(new String(result));
}
}
2.将字符串转换为字符数组:用户输入需要反转的字符串。(个人建议)
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
String input = "GeeksForGeeks";
// convert String to character array
// by using toCharArray
char[] try1 = input.toCharArray();
for (int i = try1.length-1; i>=0; i--)
System.out.print(try1[i]);
}
}
3.使用ArrayList对象:使用toCharArray()内置方法将输入字符串转换为字符数组。然后,将数组的字符添加到ArrayList对象中。Java还为Collections类内置了reverse()方法。由于Collections类reverse()方法接受一个列表对象,为了反转列表,我们将传递LinkedList对象,这是一种字符列表类型。
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString{
public static void main(String[] args)
{
String input = "Geeks For Geeks";
char[] hello = input.toCharArray();
List<Character> trial1 = new ArrayList<>();
for (char c: hello)
trial1.add(c);
Collections.reverse(trial1);
ListIterator li = trial1.listIterator();
while (li.hasNext())
System.out.print(li.next());
}
}
由于下面的方法(使用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]);
}
}
}
输出:
keetarp
它会得到你输入的值,并反向返回;)
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;
}
对于不允许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);
}