I can't seem to figure out how to reverse the order of the letters in a string. This is what i have so far...

public String reverse(String normal)
	{
		//reverse the letters in string
		
		char last; //last letter of string
		int leng = 0; //length of string
		int i;
		
		for(i = 0; i < leng; i = i - 1)
		{
		leng = normal.length();
		last = normal.charAt(leng - 1);
		}
		
		String reversed = last;
		
	return reversed
	}
public String reverse(String normal)
{
//reverse the letters in string

int length = normal.length(); //length of string
StringBuffer result = new StringBuffer(length); 
int i;

for(i = length - 1; i>=0; i--)
{
   result.append(normal.charAt(i));
}

return result.toString();
}

This does not work with a test class. It just returns the word the user inputs and does not reverse it.

This is how I would do it:

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

		//extract the last char
		String lastChar = arg.substring(arg.length()-1,arg.length());
		
		
		//extract the remaining chars
		String remainingString = arg.substring(0, arg.length() -1);

		tmp = lastChar + reverse(remainingString);
		return tmp;
		
		
	}
  }
}
import java.io.*;


public class TestReverse
{
	public static void main(String[] args) throws IOException
 	{
		System.out.println("Enter a line to be reversed");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String inData;
		inData = br.readLine();
		ReverseString rs = new ReverseString();
		System.out.println("Reversed: " + rs.reverse(inData));	
	}
}

>This is how I would do it
You would use a recursive function for a problem clearly unsuited to a recursive solution? That's a shame.

>This is how I would do it
You would use a recursive function for a problem clearly unsuited to a recursive solution? That's a shame.

You have a better way?

>You have a better way?
As a matter of fact, I do:

public String reverse ( String s )
{
  StringBuffer buffer = new StringBuffer ( s );

  return buffer.reverse().toString();
}

Though that probably won't work for homework. The obvious way is to use a loop, but because Strings are immutable you need to either do something stupid, or perform conversions. One conversion is using an array:

public String reverse ( String s )
{
  int len = s.length();
  char rev = new char[len];

  for ( int i = 0; i < len; i++ )
    rev[i] = s.charAt ( len - i - 1 );

  return new String ( rev );
}

Both of these are considerably better than recursion, and I can think of at least half a dozen more variations on this theme.

>You have a better way?
As a matter of fact, I do:

public String reverse ( String s )
{
  StringBuffer buffer = new StringBuffer ( s );

  return buffer.reverse().toString();
}

Though that probably won't work for homework. The obvious way is to use a loop, but because Strings are immutable you need to either do something stupid, or perform conversions. One conversion is using an array:

public String reverse ( String s )
{
  int len = s.length();
  char rev = new char[len];

  for ( int i = 0; i < len; i++ )
    rev[i] = s.charAt ( len - i - 1 );

  return new String ( rev );
}

Both of these are considerably better than recursion, and I can think of at least half a dozen more variations on this theme.

I guess your right. This is a much better way. At first I was thinking that although rucursion might not be the best answer but sometimes clarity and ease is the overriding concerne. Although your method was actually more clearer and easier to understand than mine.

Hello...

I've been following this post, but still have not figured out how to make it work.

If I simply want the user to input a phrase, like "Hello neighbor", how could I get it to display in reverse, as in "robhgien olleH"?

people don't you see that person is just learning ! ! !

Has no clue about buffers, streams, etc

think as beginners, not like overworked crazy programmers

for(int i = normal.length; i < 0; i--)
{
	last = normal.charAt( i);
	reversed += last;
}

Think like a thinking person and look around in the API docs.
You can do it with a single method call.

Think like a thinking person and look around in the API docs.
You can do it with a single method call.

no need for this mate, I know you all try to help, I try to do so too if I can, but sometimes you people ( prefesional programers) forget that there are people which just learning, following lecture notes or a book. Going around java api docs and looking for functions in early stage is imposible. You don't know what you looking for, you don't know where to start. Can you remember your self in early stages, learning any language

yes, I can remember that. And I'm still constantly learning after programming (first as a student and now professionally) for almost 20 years now.

I was, and still am, constantly with my head down in books and websites/docsets (and previously magazines, before they all devolved into nothing more than paid advertising).

That's why I told you to look in the documentation. The answer is there, and in a rather obvious place too.

import java.util.StringTokenizer;

public class rev {
	public static void main(String[] args) {
		
		String strLine = "Java Reverse string by word example";

		//specify delimiter as " " space
		StringTokenizer str = new StringTokenizer(strLine, " ");
		String compare = "by";
		String addString = "";

		while(str.hasMoreTokens())
		{
			String temp = str.nextToken();
			if (compare.equals( temp))
			{
				temp= "for";
			}
			addString = addString + " " + temp;
		}
		System.out.println("Sentence with replaced word  : " + addString);
	}
}

@anishpandey just summarize what you just did

  1. Posted in 4 years old thread
  2. Ignored original request (question was string reverse letters, not sentence reverse)
  3. Ignored use of tags on the forum
  4. Double posted same poor formatted code with no comments or suggestions at all

Result, thread closed.

I hope the below code helps !

StringBuffer buffer = new StringBuffer ();

for (int i=0;i<word.length();i++) {
buffer.append(word.substring(word.length()-i-1,word.length()-i));
}

How about this code? This is more efficient in space as well as time.

import java.io.*;

public class mainClass1{
    static void reverse(char[] stringTobeReversed)
    {
        System.out.println(stringTobeReversed);
        char temp;
        for (int i=0; i<(stringTobeReversed.length)/2;i++ )
        {
            temp = stringTobeReversed[i];
            stringTobeReversed[i] = stringTobeReversed[stringTobeReversed.length-i-1];
            stringTobeReversed[stringTobeReversed.length-i-1] = temp;
        }
        System.out.println(stringTobeReversed);
    }

    public static void main(String[] args)
    {
        char[] stringTobeReversed = "This is a string to be reversed".toCharArray();
        reverse(stringTobeReversed);
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.