Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

What is the mistake in this logic of reversing a string?

0 votes
class Reverse_String
{
    public static void main(String s)
    {
        String rs = "";
        s = " " + s;
        char c;
        int l = s.length();
        for (int i=(l-1); i>=0; i--)
        {
            c = s.charAt(i);
            if (i==' ')
            {
                rs = rs + " " + s.substring(i+1,l);
                s = s.substring(0,i);
                l = i;
            }
        }
        System.out.println(rs);
    }
}

 

asked by Anshul

2 Answers

0 votes

The statement 

   if (i==' ')

should be changed to

   if (c==' ')

 

The corrected program will be 

class Reverse_String {

    public static void main(String s) {
        String rs = "";
        s = " " + s;
        char c;
        int l = s.length();
        for (int i = (l - 1); i >= 0; i--) {
            c = s.charAt(i);
            if (c == ' ') {
                rs = rs + " " + s.substring(i + 1, l);
                s = s.substring(0, i);
                l = i;
            }
        }
        System.out.println(rs);
    }
}

 

answered by Ranjith (2,408 points)
Thank you so much
0 votes

I think this code will also work:

import java.util.Scanner;

public class fortest {
	    public static void main(String args[])
	    {
	       Scanner sc = new Scanner(System.in);
	       System.out.println("Enter string");
	       String str=sc.nextLine();
	       char ch;
	       String reverse="";
	       for(int i=str.length()-1;i>=0;i--) {
	    	  ch=str.charAt(i);
	    	  reverse=reverse+ch;
	       }
	       System.out.println(reverse);
               sc.close();
	    }
}
	       

If there is any error during runtime or output, please inform.

answered by Soham Thakurata (336 points)
...