如何在不使用任何API的情况下撤消字符串,例如reverse()
,length()
,toCharArray()
,charAt()
答案 0 :(得分:6)
如果您只想打印反向字符串,则可以在
之前添加Right-to-left override字符public static void printReversed(String s){
System.out.println("\u202E"+s);
}
用法
printReversed("Abc");
支持Unicode的控制台上的输出
Abc
答案 1 :(得分:2)
您可以使用反射来修改基础char []数组。但这将是一个巨大的黑客。
答案 2 :(得分:2)
简单:gnirtS eht
。您也可以考虑自己使用char数组。所以,根本不使用任何类。
char[] c = {'t', 'h', 'e', ' ', 'S', 't', 'r', 'i', 'n', 'g'};
for (int i = 0; i < c.length / 2; ++i)
{
char k = c[i];
c[i] = c[c.length - i - 1];
c[c.length - i - 1] = k;
}
或(警告,没有国际支持):
byte[] c = "the String".getBytes();
for (int i = 0; i < c.length / 2; ++i)
{
byte k = c[i];
c[i] = c[c.length - i - 1];
c[c.length - i - 1] = k;
}
String result = new String (c);
答案 3 :(得分:2)
另一种基于正则表达式的答案。两个步骤:
代码
String input = "Hello";
// brute force the length
int length = 0;
String dots = null;
do {
length++;
dots = "";
for (int i = 0; i < length; i++) {
dots += ".";
}
} while (!input.matches(dots));
// build reversing regex
StringBuilder capture = new StringBuilder();
StringBuilder replace = new StringBuilder();
for (int i = 0; i < length; i++) {
capture.append("(.)");
replace.append("$");
replace.append(length - i);
}
input = input.replaceFirst(capture.toString(), replace.toString());
System.out.println(input);
答案 4 :(得分:1)
我可以在没有reverse(),length(),toCharArray(),charAt()的情况下管理的唯一方法是在空字符串上使用split()获取字符数组,然后反向连接。
public class StackOverflow21023506 {
public static void main(String[] args) {
String result = "";
for (String each : "Hello".split("")) {
result = each + result;
}
System.out.println(result);
}
}
输出
olleH
答案 5 :(得分:1)
我认为这是一种挑战,所以这是一个更糟糕的尝试:
public static void main(String[] args)
{
String str = "qmsfdj";
String result = "";
try
{
int i = 0;
while (true)
{
result = str.substring(i, i + 1) + result;
++i;
}
} catch (Exception e) {}
System.out.println(result);
}
答案 6 :(得分:1)
Regexp救援!我们的想法是将第一个字符替换为最后一个字符,并使用相反的内容递归地替换它们之间的所有内容。
import java.util.regex.*;
class Reverse {
private static final Pattern REVERSER = Pattern.compile("^(.)(.*)(.)$",
Pattern.DOTALL);
public static void main(String[] args) {
System.out.println(reverse(args.length == 0
? "Why am I doing this?"
: args[0]));
}
public static String reverse(String s){
Matcher m = REVERSER.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(3) +
reverse(m.group(2)) +
m.group(1));
}
m.appendTail(sb);
return sb.toString();
}
}
答案 7 :(得分:1)
import java.nio.CharBuffer;
public class Reverse {
public static void main(String[] args) {
String str = "hello world!";
CharBuffer cb = CharBuffer.wrap(str);
int len = cb.limit();
String rev = "";
while (len-- > 0) rev += cb.get(len);
System.out.printf("[%s]\n", rev);
}
}
然后
$ javac Reverse.java && java -ea Reverse
[!dlrow olleh]