Java 在不使用任何预定义函数的情况下打印任何字符串的反转?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2612976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing reverse of any String without using any predefined function?
提问by Sanjeev
How to print the reverse of the String java is object orientated language
without using any predefined function like reverse()
?
如何在java is object orientated language
不使用任何预定义函数的情况下打印字符串的反转reverse()
?
采纳答案by Itay Maman
You can do it either recursively or iteratively (looping).
您可以递归或迭代(循环)执行此操作。
Iteratively:
迭代:
static String reverseMe(String s) {
StringBuilder sb = new StringBuilder();
for(int i = s.length() - 1; i >= 0; --i)
sb.append(s.charAt(i));
return sb.toString();
}
Recursively:
递归地:
static String reverseMe(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
}
回答by Paulo Santos
First of all: Why reinvent the wheel?
首先:为什么要重新发明轮子?
That being said: Loop from the length of the string to 0 and concatenate into another string.
话虽如此:从字符串的长度循环到 0 并连接到另一个字符串。
回答by Marc Gravell
Well, printing itselfwould suggest a predefined function...
好吧,打印本身会建议一个预定义的功能......
Presumably, though, you could obtain the characters and concatenate them manually in reverse (i.e. loop over it backwards). Of course, you could say concatenationis a predefined function... so maybe the char array itself. But again... why?
不过,据推测,您可以获得字符并反向手动连接它们(即向后循环)。当然,你可以说串联是一个预定义的函数……所以也许是 char 数组本身。但是……为什么?
Is the source allowed to contain "egaugnal detatneiro tcejbo si avaj" ;-p
源是否允许包含“egaugnal detatneiro tcejbo si avaj”;-p
Also - note that string reversal is actually pretty complex if you consider unicode combining characters, surrogate pairs, etc. You should note the caveat that most string reversal mechanisms will only deal with the more common cases, but may struggle with i18n.
另外 - 请注意,如果您考虑 unicode 组合字符、代理对等,字符串反转实际上非常复杂。您应该注意,大多数字符串反转机制只会处理更常见的情况,但可能会与 i18n 斗争。
回答by codaddict
How about a simple traverse from the end of the string to the beg:
从字符串的末尾到 beg 的简单遍历如何:
void printRev(String str) {
for(int i=str.length()-1;i>=0;i--)
System.out.print(str.charAt(i));
}
回答by Adriaan Koster
This is the simplest solution:
这是最简单的解决方案:
System.out.print("egaugnal detatneiro tcejbo si avaj");
回答by polygenelubricants
Here's a recursive solution that just prints the string in reverse order. It should be educational if you're trying to learn recursion. I've also made it "wrong" by actually having 2 print
statements; one of them should be commented out. Try to figure out which mentally, or just run experiments. Either way, learn from it.
这是一个递归解决方案,它只是以相反的顺序打印字符串。如果你想学习递归,它应该是有教育意义的。我实际上有 2 个print
陈述,这也使它“错误” ;其中之一应该被注释掉。试着在心理上弄清楚哪个,或者只是进行实验。无论哪种方式,都要从中学习。
static void printReverse(String s) {
if (!s.isEmpty()) {
System.out.print(s.substring(0, 1));
printReverse(s.substring(1));
System.out.print(s.substring(0, 1));
}
}
Bonus points if you answer these questions:
回答以下问题可加分:
- What is its stack requirement? Is it prone to stack overflow?
- Is it a tail recursion?
回答by jeet
final String s = "123456789";
final char[] word = s.toCharArray();
final int l = s.length() - 2;
final int ll = s.length() - 1;
for (int i = 0; i < l; i++) {
char x = word[i];
word[i] = word[ll - i];
word[ll - i] = x;
}
System.out.println(s);
System.out.println(new String(word));
You can do it either recursively or iteratively (looping).
您可以递归或迭代(循环)执行此操作。
Iteratively:
迭代:
static String reverseMe(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; --i)
sb.append(s.charAt(i));
return sb.toString();
}
Recursively:
递归地:
static String reverseMe(String s) {
if (s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(1));
}
Integer i = new Integer(15);
test(i);
System.out.println(i);
test(i);
System.out.println(i);
public static void test (Integer i) {
i = (Integer)i + 10;
}
回答by user1138509
String a="Siva";
for(int i=0;i<=a.length()-1;i++){
System.out.print(a.charAt(i));
}
for(int i = a.length() - 1; i >= 0; --i){
System.out.println(a.charAt(i));
}
回答by Mick Sear
I had this a while back, and having answered with the obvious StringBuffer.reverse() answer, they then asked 'Can you reverse a char array without using those API methods and achieve the result without spooling into a new char array?'
不久前我遇到了这个问题,并回答了明显的 StringBuffer.reverse() 答案,然后他们问“你能否在不使用这些 API 方法的情况下反转 char 数组并在不假脱机成新的 char 数组的情况下实现结果?”
At the time I recognised that I only needed to iterate over half the length of the char array, but made a bit of a hash of explaining the actual code that needed to go into it (it was a verbal question). Anyway, I tried it when I got home and came up with this:
当时我意识到我只需要迭代 char 数组长度的一半,但是对解释需要进入它的实际代码做了一些散列(这是一个口头问题)。无论如何,我回到家后尝试了一下,并想出了这个:
public class StringReverse {
public static void main(String[] args){
String a = "String";
char[] aChar = a.toCharArray();
for (int i = (aChar.length-1)/2 ; i >= 0 ; i--){
int posA = i;
int posB = (aChar.length-1-i);
char tmpA = aChar[posA];
char tmpB = aChar[posB];
System.out.println("Setting " + posA + " to " + tmpB);
System.out.println("Setting " + posB + " to " + tmpA);
aChar[posA] = tmpB;
aChar[posB] = tmpA;
}
System.out.println(aChar);
}
}
You can obviously achieve this with less code, but I think the temporary assignments in the method make it more clear what the code is doing.
你显然可以用更少的代码来实现这一点,但我认为方法中的临时赋值可以更清楚地说明代码在做什么。
Outputs something like:
输出类似:
Setting 2 to i
Setting 3 to r
Setting 1 to n
Setting 4 to t
Setting 0 to g
Setting 5 to S
gnirtS
More of an interview question than a homework question, I'd say.
我会说,与其说是家庭作业问题,不如说是面试问题。
回答by neeraj bhadouria
public class ReverseString {
public static void main(String [] args) {
String s = "reverse string" ;
String b = "";
for (int i = 0; i < s.length(); i++ ){
b= b + s.substring(s.length()-1-i, s.length()-i);
}
System.out.println(b);
}