打印任何字符串的反向而不使用任何预定义函数?

时间:2022-09-24 20:48:29

How to print the reverse of the String java is object orientated language without using any predefined function like reverse()?

如何在不使用任何预定义函数(如reverse()的情况下打印字符串java的反向是面向对象的语言?

34 个解决方案

#1


46  

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

#2


53  

This is the simplest solution:

这是最简单的解:

System.out.print("egaugnal detatneiro tcejbo si avaj");

#3


8  

Well, printing itself would 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 concatenation is 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发生冲突。

#4


6  

How about a simple traverse from the end of the string to the beg:

从绳子的末端到乞丐的简单的穿越怎么样:

void printRev(String str) {
 for(int i=str.length()-1;i>=0;i--)
  System.out.print(str.charAt(i));
}

#5


5  

String reverse(String s) {
  int legnth = s.length();
  char[] arrayCh = s.toCharArray();
  for(int i=0; i< length/2; i++) {
      char ch = s.charAt(i);
      arrayCh[i] = arrayCh[legnth-1-i];
      arrayCh[legnth-1-i] = ch;
  } 
 return new String(arrayCh);
}

#6


3  

public class StringReverse {

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

Prints the reversed string of the input.

打印输入的反向字符串。

#7


3  

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,并连接到另一个字符串中。

#8


2  

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

#9


1  

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.

这是一个递归的解决方案,它只是以相反的顺序打印字符串。如果你想学习递归,这应该是很有教育意义的。我也说错了,实际上有两个打印声明;其中一个应该被注释掉。试着在头脑中找出哪个,或者只是进行实验。不管怎样,都要从中学习。

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?
  • 是尾部递归吗?

#10


1  

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

#11


1  

public class StringReverse {
    public static void main(String ar[]){
        System.out.println(reverseMe("SRINIVAS"));
    }
    static String reverseMe(String s){
        StringBuffer sb=new StringBuffer();
        for(int i=s.length()-1;i>=0;--i){
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}

#12


1  

private void rev() {
    String st="hello";
    String b="";

    for(int i=st.length()-1;i>=0;i--){
        b=b+st.charAt(i);
    }

    System.out.println("reverse:::"+b);
}

#13


1  

Try this:

试试这个:

public  class Test {

    public static void main(String[] args) {
        String s = "welcome";   
    for( int i=0, j = (s.length())-1; i <= j; j-- ) {   
      char c=s.charAt(j);
      System.out.print(c);
    }
    }
}

#14


1  

What is suprising is that most of the answers are wrong! When Unicode is used. Seems like no one understands that java uses UTF-16 under the hood for Text encoding.

令人惊讶的是,大多数答案都是错的!当使用Unicode。似乎没有人知道java在文本编码的引擎盖下使用UTF-16。

Here is my simple answer.

这是我的简单答案。

static String reverseMe(String s) {
   StringBuilder sb = new StringBuilder();

   int count = s.codePointCount(0,s.length());
   for(int i = count - 1; i >= 0; --i)
     sb.append(Character.toChars(s.codePointAt(i)));

   return sb.toString();
 }

#15


1  

this is the best solution for this

这是最好的解决方案。

public class String_rev {
public static void main(String[] args) {
    String str="Karan Rajput";
    int ln=str.length();
    for (int i = ln; i > 0; i--) {
        System.out.print(str.charAt(i-1));
    }
}

}

}

#16


0  

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

#17


0  

public static void main(String[] args) {


    String str = "hello world here I am";

    StringTokenizer strToken = new StringTokenizer(str);
    int token = strToken.countTokens();
    String str1 [] = new String[token];

    char chr[] = new char[str.length()];
    int counter = 0;

    for(int j=0; j < str.length(); j++) {

        if(str.charAt(j) != ' ') {
            chr[j] = str.charAt(j);
        }else {
            str1[counter++] = new String(chr).trim();
            chr = new char[str.length()];
        }
    }
    str1[counter++] = new String(chr).trim();

    for(int i=str1.length-1; i >= 0 ; i--) {
        System.out.println(str1[i]);
    }
}

O/P is: am I here world hello

O/P是:我在这里世界你好

#18


0  

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.

我觉得与其说是家庭作业问题,不如说是面试问题。

#19


0  

public String reverse(String arg)
{
    String tmp = null;
    if (arg.length() == 1)
    {
        return arg;
    }

    else
    {

        String lastChar = arg.substring(arg.length()-1,arg.length());

        String remainingString = arg.substring(0, arg.length() -1);

        tmp = lastChar + reverse(remainingString);
        return tmp;


    }
}

#20


0  

import java.util.*;
public class Restring {

public static void main(String[] args) {
  String input,output;
  Scanner kbd=new Scanner(System.in);
  System.out.println("Please Enter a String");
  input=kbd.nextLine();
  int n=input.length();

  char tmp[]=new char[n];
  char nxt[]=new char[n];

  tmp=input.toCharArray();
  int m=0;
  for(int i=n-1;i>=0;i--)
  {
      nxt[m]=tmp[i];
      m++;
  }

  System.out.print("Reversed String is   ");
  for(int i=0;i<n;i++)
  {
      System.out.print(nxt[i]);
  }

}

#21


0  

 public class ReverseWithoutStringAPI {

public static void main(String[] args) {

      String st="hello";

        StringBuffer b=new StringBuffer();

        for(int i=st.length()-1;i>=0;i--){

            b.append(st.charAt(i)); }

        System.out.println("reverse:::"+b);
}
}

#22


0  

String x = "stack overflow";
String reversed = "";
for(int i = x.length()-1 ; i>=0; i--){
    reversed = reversed+ x.charAt(i);
}
System.out.println("reversed string is : "+ reversed);

#23


0  

Here you go:

给你:

public static void main (String[] args) {
    System.out.println(reverserString("Akshay"));
}

private static String reverserString(String src) {
    char[] sArr = src.toCharArray();
    char[] dArr = new char[sArr.length];
    for(int i=sArr.length; i>0; i--) {
        dArr[sArr.length-i] = sArr[i-1];
    }

    return new String(dArr);
}

#24


0  

public class MyStack {
   private int maxSize;
   private char[] stackArray;
   private int top;
   public MyStack(int s) {
      maxSize = s;
      stackArray = new char[maxSize];
      top = -1;
   }
   public void push(char j) {
      stackArray[++top] = j;
   }
   public char pop() {
      return stackArray[top--];
   }
   public char peek() {
      return stackArray[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
   public boolean isFull() {
      return (top == maxSize - 1);
   }
   public static void main(String[] args) {
      MyStack theStack = new MyStack(10);
      String s="abcd";
      for(int i=0;i<s.length();i++)
      theStack.push(s.charAt(i));
      for(int i=0;i<s.length();i++)
      System.out.println(theStack.pop());

    }

#25


0  

public class ReverseString {

public static void main(String[] args) {

    reverseString("HELLO");
}

public static String reverseString(String s){
    char []arr=s.toCharArray();
    for(int i= (arr.length)-1;i>=0;i--){
        System.out.print(arr[i]);
    }
    String str=String.copyValueOf(arr);
    return str;
}

#26


0  

package com.ofs;

public class ReverseWordsInString{
public static void main(String[] args) {

    String str = "welcome to the new world and how are you feeling ?";

    // Get the Java runtime
    Runtime runtime = Runtime.getRuntime();
    // Run the garbage collector
    runtime.gc();
    // Calculate the used memory
    long firstUsageMemory = runtime.totalMemory() - runtime.freeMemory();
    System.out.println("Used memory in bytes: " + firstUsageMemory);
    System.out.println(str);
    str = new StringBuffer(str).reverse().toString();
    int count = 0;
    int preValue = 0;
    int lastspaceIndexVal = str.lastIndexOf(" ");
    int strLen = str.length();
    for (int i = 0; i < strLen - 1; i++) {
        if (Character.isWhitespace(str.charAt(i))) {
            if (i - preValue == 1 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 2 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 3 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 4 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 5 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i - 2, i - 1) + str.charAt(i - 3)
                        + str.charAt(i - 3) + str.charAt(i - 5)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 6 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 7 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 8 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.charAt(i - 8) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 2 && count != 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 3 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 4 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 5 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 6 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 7 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 8 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            }
            if (lastspaceIndexVal == preValue) {
                if (strLen - lastspaceIndexVal == 2 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 3 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 4 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3);
                    preValue = i;
                    count++;
                } else if (strLen - lastspaceIndexVal == 5 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 6 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5);
                    preValue = i;
                    count++;
                } else if (strLen - lastspaceIndexVal == 7 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5)
                            + str.charAt(strLen - 6);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 8 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5)
                            + str.charAt(strLen - 6)
                            + str.charAt(strLen - 7);
                    preValue = i;
                }
            }
        }
    }
    runtime.gc();
    // Calculate the used memory
    long SecondaryUsageMemory = runtime.totalMemory()
            - runtime.freeMemory();
    System.out.println("Used memory in bytes: " + SecondaryUsageMemory);
    System.out.println(str);
}
}

#27


0  

ReverseString.java

ReverseString.java

public class ReverseString {
    public static void main(String[] args) {
        String str = "Ranga Reddy";
        String revStr = reverseStr(str);
        System.out.println(revStr);     
    }

    // Way1 - Recursive
    public static String reverseStr(String str) {
        char arrStr[] = reverseString(0, str.toCharArray());
        return new String(arrStr);
    }

    private static char[] reverseString(int charIndex, char[] arr) {     
        if (charIndex > arr.length - (charIndex+1)) {
          return arr;
        }

        int startIndex = charIndex;
        int endIndex = arr.length - (charIndex+1);

        char temp = arr[startIndex];        
        arr[startIndex] = arr[endIndex];
        arr[endIndex] = temp;      
        charIndex++;       
        return reverseString(charIndex++, arr);
    }

    // Way2
    private static String strReverse(String str) {
        char ch[] = new char[str.length()];
        for (int i = str.length() - 1, j = 0; i >= 0; i--) {
            ch[j++] = str.charAt(i);
        }
        return new String(ch);
    }
}

#28


0  

It is very simple using while loop

使用while循环非常简单。

public class Test {
public static void main(String[] args) {
    String name = "subha chandra";
    int len = name.length();
    while(len > 0){
        len--;
        char c = name.charAt(len);
        System.out.print(c); // use String.valueOf(c) to convert char to String
    }
}    
}

#29


0  

import java.util.Scanner;
public class StringReverse {
    public static void main(String[] args) {
        //Read user Data From Console
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Your String:");
        //Take an String so that it can Store the string data 
        String s1 = sc.nextLine();
        //split the string and keep in an array
        String[] s2 = s1.split(" ");
        String s3 = " ";
        //reverse  the string and placed in an String s3
        for (int i = 0; i < s2.length; i++) {
            for (int j= s2[i].length()-1;j>=0;j--) {
                s3 += s2[i].charAt(j);
            }//for
            s3 += " ";
        }//for

        System.out.println("After Reverse: "+s3);

    }//main
}//StringReverse

#30


0  

It can be done this way also

也可以这样做。

char c[]=str.toCharArray();
  int i=c.lenght-1;
public void printReverseString(char[] c, int i){
       if(i==-1) return;
       System.out.println(c[i]);
       printReverseString(c,--i);
   }   

#1


46  

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

#2


53  

This is the simplest solution:

这是最简单的解:

System.out.print("egaugnal detatneiro tcejbo si avaj");

#3


8  

Well, printing itself would 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 concatenation is 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发生冲突。

#4


6  

How about a simple traverse from the end of the string to the beg:

从绳子的末端到乞丐的简单的穿越怎么样:

void printRev(String str) {
 for(int i=str.length()-1;i>=0;i--)
  System.out.print(str.charAt(i));
}

#5


5  

String reverse(String s) {
  int legnth = s.length();
  char[] arrayCh = s.toCharArray();
  for(int i=0; i< length/2; i++) {
      char ch = s.charAt(i);
      arrayCh[i] = arrayCh[legnth-1-i];
      arrayCh[legnth-1-i] = ch;
  } 
 return new String(arrayCh);
}

#6


3  

public class StringReverse {

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

Prints the reversed string of the input.

打印输入的反向字符串。

#7


3  

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,并连接到另一个字符串中。

#8


2  

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

#9


1  

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.

这是一个递归的解决方案,它只是以相反的顺序打印字符串。如果你想学习递归,这应该是很有教育意义的。我也说错了,实际上有两个打印声明;其中一个应该被注释掉。试着在头脑中找出哪个,或者只是进行实验。不管怎样,都要从中学习。

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?
  • 是尾部递归吗?

#10


1  

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

#11


1  

public class StringReverse {
    public static void main(String ar[]){
        System.out.println(reverseMe("SRINIVAS"));
    }
    static String reverseMe(String s){
        StringBuffer sb=new StringBuffer();
        for(int i=s.length()-1;i>=0;--i){
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}

#12


1  

private void rev() {
    String st="hello";
    String b="";

    for(int i=st.length()-1;i>=0;i--){
        b=b+st.charAt(i);
    }

    System.out.println("reverse:::"+b);
}

#13


1  

Try this:

试试这个:

public  class Test {

    public static void main(String[] args) {
        String s = "welcome";   
    for( int i=0, j = (s.length())-1; i <= j; j-- ) {   
      char c=s.charAt(j);
      System.out.print(c);
    }
    }
}

#14


1  

What is suprising is that most of the answers are wrong! When Unicode is used. Seems like no one understands that java uses UTF-16 under the hood for Text encoding.

令人惊讶的是,大多数答案都是错的!当使用Unicode。似乎没有人知道java在文本编码的引擎盖下使用UTF-16。

Here is my simple answer.

这是我的简单答案。

static String reverseMe(String s) {
   StringBuilder sb = new StringBuilder();

   int count = s.codePointCount(0,s.length());
   for(int i = count - 1; i >= 0; --i)
     sb.append(Character.toChars(s.codePointAt(i)));

   return sb.toString();
 }

#15


1  

this is the best solution for this

这是最好的解决方案。

public class String_rev {
public static void main(String[] args) {
    String str="Karan Rajput";
    int ln=str.length();
    for (int i = ln; i > 0; i--) {
        System.out.print(str.charAt(i-1));
    }
}

}

}

#16


0  

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

#17


0  

public static void main(String[] args) {


    String str = "hello world here I am";

    StringTokenizer strToken = new StringTokenizer(str);
    int token = strToken.countTokens();
    String str1 [] = new String[token];

    char chr[] = new char[str.length()];
    int counter = 0;

    for(int j=0; j < str.length(); j++) {

        if(str.charAt(j) != ' ') {
            chr[j] = str.charAt(j);
        }else {
            str1[counter++] = new String(chr).trim();
            chr = new char[str.length()];
        }
    }
    str1[counter++] = new String(chr).trim();

    for(int i=str1.length-1; i >= 0 ; i--) {
        System.out.println(str1[i]);
    }
}

O/P is: am I here world hello

O/P是:我在这里世界你好

#18


0  

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.

我觉得与其说是家庭作业问题,不如说是面试问题。

#19


0  

public String reverse(String arg)
{
    String tmp = null;
    if (arg.length() == 1)
    {
        return arg;
    }

    else
    {

        String lastChar = arg.substring(arg.length()-1,arg.length());

        String remainingString = arg.substring(0, arg.length() -1);

        tmp = lastChar + reverse(remainingString);
        return tmp;


    }
}

#20


0  

import java.util.*;
public class Restring {

public static void main(String[] args) {
  String input,output;
  Scanner kbd=new Scanner(System.in);
  System.out.println("Please Enter a String");
  input=kbd.nextLine();
  int n=input.length();

  char tmp[]=new char[n];
  char nxt[]=new char[n];

  tmp=input.toCharArray();
  int m=0;
  for(int i=n-1;i>=0;i--)
  {
      nxt[m]=tmp[i];
      m++;
  }

  System.out.print("Reversed String is   ");
  for(int i=0;i<n;i++)
  {
      System.out.print(nxt[i]);
  }

}

#21


0  

 public class ReverseWithoutStringAPI {

public static void main(String[] args) {

      String st="hello";

        StringBuffer b=new StringBuffer();

        for(int i=st.length()-1;i>=0;i--){

            b.append(st.charAt(i)); }

        System.out.println("reverse:::"+b);
}
}

#22


0  

String x = "stack overflow";
String reversed = "";
for(int i = x.length()-1 ; i>=0; i--){
    reversed = reversed+ x.charAt(i);
}
System.out.println("reversed string is : "+ reversed);

#23


0  

Here you go:

给你:

public static void main (String[] args) {
    System.out.println(reverserString("Akshay"));
}

private static String reverserString(String src) {
    char[] sArr = src.toCharArray();
    char[] dArr = new char[sArr.length];
    for(int i=sArr.length; i>0; i--) {
        dArr[sArr.length-i] = sArr[i-1];
    }

    return new String(dArr);
}

#24


0  

public class MyStack {
   private int maxSize;
   private char[] stackArray;
   private int top;
   public MyStack(int s) {
      maxSize = s;
      stackArray = new char[maxSize];
      top = -1;
   }
   public void push(char j) {
      stackArray[++top] = j;
   }
   public char pop() {
      return stackArray[top--];
   }
   public char peek() {
      return stackArray[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
   public boolean isFull() {
      return (top == maxSize - 1);
   }
   public static void main(String[] args) {
      MyStack theStack = new MyStack(10);
      String s="abcd";
      for(int i=0;i<s.length();i++)
      theStack.push(s.charAt(i));
      for(int i=0;i<s.length();i++)
      System.out.println(theStack.pop());

    }

#25


0  

public class ReverseString {

public static void main(String[] args) {

    reverseString("HELLO");
}

public static String reverseString(String s){
    char []arr=s.toCharArray();
    for(int i= (arr.length)-1;i>=0;i--){
        System.out.print(arr[i]);
    }
    String str=String.copyValueOf(arr);
    return str;
}

#26


0  

package com.ofs;

public class ReverseWordsInString{
public static void main(String[] args) {

    String str = "welcome to the new world and how are you feeling ?";

    // Get the Java runtime
    Runtime runtime = Runtime.getRuntime();
    // Run the garbage collector
    runtime.gc();
    // Calculate the used memory
    long firstUsageMemory = runtime.totalMemory() - runtime.freeMemory();
    System.out.println("Used memory in bytes: " + firstUsageMemory);
    System.out.println(str);
    str = new StringBuffer(str).reverse().toString();
    int count = 0;
    int preValue = 0;
    int lastspaceIndexVal = str.lastIndexOf(" ");
    int strLen = str.length();
    for (int i = 0; i < strLen - 1; i++) {
        if (Character.isWhitespace(str.charAt(i))) {
            if (i - preValue == 1 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 2 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 3 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 4 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 5 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i - 2, i - 1) + str.charAt(i - 3)
                        + str.charAt(i - 3) + str.charAt(i - 5)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 6 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 7 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 8 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.charAt(i - 8) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 2 && count != 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 3 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 4 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 5 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 6 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 7 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 8 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            }
            if (lastspaceIndexVal == preValue) {
                if (strLen - lastspaceIndexVal == 2 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 3 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 4 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3);
                    preValue = i;
                    count++;
                } else if (strLen - lastspaceIndexVal == 5 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 6 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5);
                    preValue = i;
                    count++;
                } else if (strLen - lastspaceIndexVal == 7 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5)
                            + str.charAt(strLen - 6);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 8 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5)
                            + str.charAt(strLen - 6)
                            + str.charAt(strLen - 7);
                    preValue = i;
                }
            }
        }
    }
    runtime.gc();
    // Calculate the used memory
    long SecondaryUsageMemory = runtime.totalMemory()
            - runtime.freeMemory();
    System.out.println("Used memory in bytes: " + SecondaryUsageMemory);
    System.out.println(str);
}
}

#27


0  

ReverseString.java

ReverseString.java

public class ReverseString {
    public static void main(String[] args) {
        String str = "Ranga Reddy";
        String revStr = reverseStr(str);
        System.out.println(revStr);     
    }

    // Way1 - Recursive
    public static String reverseStr(String str) {
        char arrStr[] = reverseString(0, str.toCharArray());
        return new String(arrStr);
    }

    private static char[] reverseString(int charIndex, char[] arr) {     
        if (charIndex > arr.length - (charIndex+1)) {
          return arr;
        }

        int startIndex = charIndex;
        int endIndex = arr.length - (charIndex+1);

        char temp = arr[startIndex];        
        arr[startIndex] = arr[endIndex];
        arr[endIndex] = temp;      
        charIndex++;       
        return reverseString(charIndex++, arr);
    }

    // Way2
    private static String strReverse(String str) {
        char ch[] = new char[str.length()];
        for (int i = str.length() - 1, j = 0; i >= 0; i--) {
            ch[j++] = str.charAt(i);
        }
        return new String(ch);
    }
}

#28


0  

It is very simple using while loop

使用while循环非常简单。

public class Test {
public static void main(String[] args) {
    String name = "subha chandra";
    int len = name.length();
    while(len > 0){
        len--;
        char c = name.charAt(len);
        System.out.print(c); // use String.valueOf(c) to convert char to String
    }
}    
}

#29


0  

import java.util.Scanner;
public class StringReverse {
    public static void main(String[] args) {
        //Read user Data From Console
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Your String:");
        //Take an String so that it can Store the string data 
        String s1 = sc.nextLine();
        //split the string and keep in an array
        String[] s2 = s1.split(" ");
        String s3 = " ";
        //reverse  the string and placed in an String s3
        for (int i = 0; i < s2.length; i++) {
            for (int j= s2[i].length()-1;j>=0;j--) {
                s3 += s2[i].charAt(j);
            }//for
            s3 += " ";
        }//for

        System.out.println("After Reverse: "+s3);

    }//main
}//StringReverse

#30


0  

It can be done this way also

也可以这样做。

char c[]=str.toCharArray();
  int i=c.lenght-1;
public void printReverseString(char[] c, int i){
       if(i==-1) return;
       System.out.println(c[i]);
       printReverseString(c,--i);
   }