Can someone give me an example on how to reverse an inputted string?

example is..when you inputted "shoes" the output would be "seohs",,then it wil determine if the inputted string is a Palindrome or not..

Check the API for the String class. There you will find many useful methods

I just wrote this for something else, so here you go.

public class reverse {

	
	public static String reverseIt(String a) {
	
		int length = a.length();
		StringBuilder reverse = new StringBuilder();
		for(int i = length; i > 0; --i) {
			char result = a.charAt(i-1);
			reverse.append(result);
		}
		return reverse.toString();
	}
	
}

That method should return the reversed string.

commented: You're long enough around to know that posting solutions is not the way we help people. Also there's a bug in your solution, so actually it isn't even a solution. -2

I am sorry to disappoint you Godstryke but next time when you want to compare Strings or in general objects use the "equals" method:

if ( reverse.reverseIt(str).equals(str) ) {
}

And please try to be a bit patient, and observative.
You have already replied to a loozax's post with the same question. In this post the question is how to reverse and in the next post was to check the code.

So personally I would be curious to see what code he has written as to comment and offer suggestions and tips, since he has already put some effort to write his own code.

I am sorry to disappoint you Godstryke but next time when you want to compare Strings or in general objects use the "equals" method:

if ( reverse.reverseIt(str).equals(str) ) {
}

And please try to be a bit patient, and observative.
You have already replied to a loozax's post with the same question. In this post the question is how to reverse and in the next post was to check the code.

So personally I would be curious to see what code he has written as to comment and offer suggestions and tips, since he has already put some effort to write his own code.

Yes, there was an error in the palindrome check and I was actually in the process of removing it. No need to get impatient with me either.

However, the reversal section has had no issues. What I have written is meant to be a sample - one way to do it.
The palindrome check is now fixed as well.

import java.util.*;

public class palindrome{
	
private static String str;

	public static void main(String [] args) {
		
		Scanner input = new Scanner(System.in);
		
		System.out.print("Enter a string: ");
		str = input.nextLine();
		System.out.println("The reverse: "+reverse.reverseIt(str));
		
	 if (reverse.reverseIt(str).equals(str)){
      System.out.println("It IS a palindrome!");
	 } else {
      System.out.println("It is NOT a palindrome!");
    }
    System.out.println();
  	}
}

Of course, the reverseIt method would work only for one-word palindromes. If you wanted to do phrases, you would have to ignore punctuation and spaces for it to work properly in most cases.

import java.util.*;

public class StringReverse
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a string: ");
		
		String s;
		s=input.nextLine();
		char arr[]=s.toCharArray();
		System.out.println("Original is :" );
		for(int i=0 ; i<arr.length ; i++)
		System.out.print(arr[i]); 
		String rev="";
		System.out.println();
		System.out.println("Length:"+ arr.length);
		for (int i=arr.length-1;i>=0;i--)
		{
			rev=rev +arr[i];
		}
	System.out.println("Reverse:\n" + rev);
	}
 }

StringBuffer has an instance method: reverse() to do the reversing job.

import java.io.*;
import javax.swing.JOptionPane;
 public class Palindrome{   

 static boolean palindromeCouplet (String s)   {
 	StringBuffer s1 = new StringBuffer(s);
 return ((s.compareTo(new String(s1.reverse()))==0) ? true :false)  ;
 	}	

 public static void main(String[] args) {	
 	while(true){
    String str=JOptionPane.showInputDialog( null,  
	"Type in a word!\nPress cancel to ternimate。",
	"IS A PALINROME",
	JOptionPane.QUESTION_MESSAGE);    
    
	if (str == null) {
	System.out.println("Bey for now");
    	break;
    	} 
JOptionPane.showMessageDialog( null,  
	"Palindrome: " + palindromeCouplet(str),
	str + " IS A PALIDROME? ",
	JOptionPane.INFORMATION_MESSAGE);  
          }
      }   
}

Does it work with Unicode?
Does it work with Unicode Indic section?

The primitive data type char in java is represented by Unicode. Therefore, the reverse() method of StringBuffer works with Unicode, i.e., works with many kinds of Characters, such Chinese, Japanese, Russian,.....

I hear that all the time. Many unicode 'gurus' are not aware how characters are represented in Indic languages. One character can have one,two, three, four, or five words (unicode characters. Say you wanted to reverse सरस्वती . You would expect the reveresed word to look like this: तीस्वरस However, this four character word is represented by seven unicode characters i.e. 14 bytes. The first and second characters have tow bytes each, but the third is 6 bytes (3 Unicode characters) and the fourth letter is foru bytes (2 Unicode characters). In some datbase indexing they recognize this byt in the challenge here of reversing the word - it fails.

Very interesting. I hadn't thought about the implications of devanagari and unicode representation for this problem.

For those who haven't looked at Indian languages, the representation is syllabic, with consonants followed by short a unless otherwise specified, and consonant clusters represented by compounding the consonant signs:
सरस्वती would be read sa-ra-sva-ti, where the final i is long. (I believe it's a woman's name, no?) What "reversing" this means is going to take some definition.
In Latin characters, the obvious reversal of "sarasvati" is "itavsaras", but apparently the expected output in Devanagari would be read more like tisvaras, or possibly "tisvarasa" (I'm not so good with knowing when the final vowel is pronounced).

These are the characters of nydas' stringas the Daniweb editor breaks them up:
स र स् व त ी

but the correct grouping, according to our informant, is:
स र स्व ती
So the problem takes on a bit more complexity. Notice the little tail on this "sa" character: स् - that means there is no following vowel, so it's just "s". So स्व is actually three characters, one of which is not visible in this representation.

String reversal now becomes a bit of a parsing problem: your tokens are "complete syllables", which have a variable length, but can be represented by a state machine.

I suppose it's easier than recognizing syllabic boundaries in English, though. That would be a bit of a hellish problem, unless you gave the computer a dictionary.

nydas, Thank you for your information. After checking with internet, one may come to the conclusion: Indic language is a very special Indian language which can not be represented by UNICODE. Perhaps it works by the combination of ISCII (Indian Standard Code for Information Interchange) and Unicode.
See MUKRI: Indic computing in Java made easy!

Obviously, Devanagari can be represented in Unicode - specifically in the range 0900–097F, according to unicode.org

jon.kiparsky and tong1: - Re Mukri. That is primitive and does not address the computing problem of arriving at say 17th character in a string and of reversing a string. Google transliteration is very good for the same purpose as Mukri - i.e. of writing words - I composed above using Google transliteration.

The problem as I defined it is that any Indic character (Hindi, Gujarati, Tamil, Telgu, etc) as a laymen sees and recognizes it, can be composed of one, two three four and even five Unicode characters. In the four letter word सु क्ष्मां त र (I have separated the characters for easy viewing), the first character सु is two U characters, the second क्ष्मां is five, त is one and र is one U character. To try and access the third character you have to skip seven Unicode characters - this is already done nicely in some software, but to try and reverse the four to र त क्ष्मां सु would require a lot of programming (I am trying it in Assembler)

Thanks for your interest

Just a quibble क्ष्मां is 7 characters by my count - the virama is a Unicode character, no?

to try and reverse the four to र त क्ष्मां सु would require a lot of programming (I am trying it in Assembler)

Have you done any work with compilers and parsers? I think you could do this in Java, and it's probably a lot easier than you think.
To begin, I notice that your syllables all break on vowels, including the implicit short a of र and त. Your little snippet suggests that a syllable is made up of

[cons][virama cons]* [[vowel-sign] [anusvara]?]?

That is, a syllable (= character) requires a consonant, followed optionally by some number of consonants, with the virama (vowel-suppression character) intervening, followed by an optional vowel sign, which may itself be followed by an optional anusvara (the little dot over the last stroke of क्ष्मां, it nasalizes the vowel).

Probably there are some other things that have to be worked in here, it's been ages since I wrote my thesis and my devanagari is very rusty, but it's a start. You could begin tokenising based on this.

For me, having to write in assembler is much easier. The need for speed is paramount, and I can easily walk backwards to combat the challenged posed by this thread.
The concept you just mentioned is easy enough to follow. However, even today I get email in one of the Hindi (Devnagari) and gujarati languages where, in a paragraph at least three words are broken at "Virama". Very annoying to see and disconcerting to know that the programmers have still not got round to the job properly. I am sure those programmers are using Java and variations thereof.

The original fault lies with the gurus who accepted a non-sysllablic solution for Unicode - It was acceptable at the time for the sake of required brevity and lack of memeory space and processor speed, but has no value to me in the modern set up Windows 7 and 8 GB windows accessibility.

Just a quibble क्ष्मां is 7 characters by my count - the virama is a Unicode character, no?

You are right - my mistake.

Bad programming can be done in any language. That's the programmer, not the language. If you want to write it in assembler, that's your business. I'm just saying, you could do it pretty easily in Java if you wanted.

For example, the little grammar I describe above would be done in a four step loop, starting at the beginning of a syllable:

1) if the first symbol isn't a consonant sign, report an error. (actually, this is wrong, because I know there are vowel-initial words in Hindi and Sanskrit, so I'm just talking about the toy grammar here) If it is a consonant-sign, accept it (put it in the output pile) and get the next symbol

2) while the next symbol is a virama, accept a consonant sign or report an error, and get the next symbol

3) if the next symbol is a vowel, accept the vowel and accept an anusvara if there is one.

4) return the sequence of symbols you've just accepted and begin again from step 1.


Granted, there is more to the grammar of syllables than this small segment, but that's about what you'd do in any case, only the details would change.
The point in outlining all of this is to plead the case: it's not the language that's the problem, it's poor programmers. If they get the logic wrong, I imagine they'd get it wrong in assembler or C or whatever else you gave them.

You are contributing the following post:
Thanks for your suggestion. The logic you have suggested is sound. I would do it in Assembler, but i would prefer to see what happensif I started in reverse from the end of the sequence.
Anyway, we are not far apart in our thinking.

I need to do pretty much the same thing but my problem is a bit more complicated . I need to reverse an input like : "Hello" and the output should be" o,lo,llo,ello,Hello "

please help !

vnaa,
In stead of reversing a string your ploblem is to write a series of sub-strings starting from the last character using the member method substring in the class String:

String s="Hello";
	for (int i=1;i<s.length()+1;i++)
	System.out.print(s.substring(s.length()-i) + ", ");
commented: Excellent solution +0
import java.io.*;
import javax.swing.*;
import java.lang.*;
class palins
{
  
  public static void main(String args[])throws IOException
  
 {  
   String q;
   int l=1;
       JOptionPane.showMessageDialog(null,"Welcome to Palindrome prog");
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     
do{ 
  
  String a=JOptionPane.showInputDialog("Enter the String");
  char[] d = a.toCharArray();
  char[] m=new char[d.length]; 
    
System.out.println("The Original String is :");
for(int i=0;i<a.length();i++)
System.out.print(""+d[i]);


for(int i=0;i<=d.length-1;i++)
m[i]=d[d.length-1-i];


System.out.println("The Reverse String is :");
for(int i=0;i<a.length();i++)
System.out.print(""+m[i]);


String str = new String(m);
System.out.print(str);
JOptionPane.showMessageDialog(null,"Reverse Sting is  "+str);

int flag=1;
for(int i=0;i<d.length;i++)
{ 
if(m[i]==d[i]) 
flag=1;
else
{
 flag=0;
 break;
   }
}

int k=1+8;
if(flag==1)
JOptionPane.showMessageDialog(null,"Its a Palindrome");
else
JOptionPane.showMessageDialog(null,"oops..Its not a Palindrome");


q=JOptionPane.showInputDialog("Do u wish to continue (y/n)?");
if(q.equalsIgnoreCase("n"))

l=JOptionPane.showConfirmDialog(null, "Are you sure?","",JOptionPane.YES_NO_OPTION);
if(l==1)
q="y";
else
break;
       } while(q.equalsIgnoreCase("y"));

JOptionPane.showMessageDialog(null,"Thanks for using my prog");

  
    }

}

String reversing in Java is very tricky. I tried to use String buffer then do a for loop from the last character up to the first. I'm just a student like you, browsing for information.

This is awful. To begin with, it's not even vaguely related to the dead thread you revived to post it in, so you're on the wrong foot to begin with. Moving along, you really ought to use the code-tags to make life easier for those trying to read your code.

But the real problem is, this is awful code. Why are you mixing swing components and command-line i/o? Why are you using int flags instead of booleans? Why are you using a loop to print a String? Why is this whole thing one long method - how is that "easy to understand"?

And what the hell happened here?

q=JOptionPane.showInputDialog("Do u wish to continue (y/n)?");
if(q.equalsIgnoreCase("n"))

l=JOptionPane.showConfirmDialog(null, "Are you sure?","",JOptionPane.YES_NO_OPTION);
if(l==1)
q="y";
else
break;
       } while(q.equalsIgnoreCase("y"));

JOptionPane.showMessageDialog(null,"Thanks for using my prog");
}

Okay, I understand you're a novice and you were trying to convert a CLI program to run in a GUI. But please don't post bad code to answer a question which wasn't asked in a long-dead thread. Okay? Great, glad that's settled.

import java.util.Scanner;
public class sortString {
    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        String s;
        String reverse="";
        System.out.println("Enter String:");
        s=input.next();
        for(int i=0;i<s.length();i++){
            reverse=s.charAt(i)+reverse;


        }
        System.out.println("Reverse String= "+reverse);

    }

}
    import java.util.Scanner;
    public class sortString {
        public static void main(String args[]){
            Scanner input=new Scanner(System.in);
            String s;
            String reverse="";
            System.out.println("Enter String:");
            s=input.next();
            for(int i=0;i<s.length();i++){
                reverse=s.charAt(i)+reverse;
                
                
            }
            System.out.println("Reverse String= "+reverse);
            
        }
    
    }

don't revive ancient (dead) threads and even when: don't just hand out code. let them do an effort themselves and help improving their work, instead of just passing your code off as theirs.

public class Trial {

public static void main(String args[]){
    String abc="Alpha";
    int length=abc.length();
    String temp="";
    for (int i=length-1;i>=0;i--){

        temp+=abc.charAt(i);
    }
    System.out.println(temp);
}

}

public class Trial {

public static void main(String args[]){
    String abc="Alpha";
    int length=abc.length();
    String temp="";
    for (int i=abc.length();i>0;i--){

        temp+=abc.substring(i-1,length);
        length--;
    }
    System.out.println(temp);
}

}

I have been working on this problem as a HW assignment. Thank you for all of the thoughtful submissions, they were a lot of help. There is a non object oriented way to do this I have discovered. It's elegent IMO but completely from experience with C based languages. Using length() and charAt() I was able to isolate the next letter in the sequence. The solution came to me once I understood the conditional would have to reject anything less than 0 (even though the loop had to begin at the String's length - 1) AND the unary operator should appear after the first letter is printed. This snippet should be helpful understanding how char position is counted and how to access chars in a String.

//Outputs esreveR
    String s = new String("Reverse");
        int i;
        for (i = s.length()-1;i>-1;){
        char c = s.charAt(i);
        System.out.print(c);
        i--;

there are a lot easier ways, too. but that is no reason to revive a thread that should 've died over a year ago.

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.