We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,939 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion
Page 2 of Article: How to reverse a string?
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..

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) + ", ");
tong1
Posting Whiz
358 posts since Jul 2010
Reputation Points: 34
Solved Threads: 72
Skill Endorsements: 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");

  
    }

}
Ahamedmubin
Newbie Poster
1 post since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

redmaiev04
Newbie Poster
5 posts since Apr 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

jon.kiparsky
Posting Virtuoso
1,849 posts since Jun 2010
Reputation Points: 383
Solved Threads: 187
Skill Endorsements: 3
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);

    }

}
Umair-Qayyum
Newbie Poster
1 post since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
    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.

stultuske
Industrious Poster
4,372 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 24

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

}

Muthu Dayalan
Newbie Poster
2 posts since Apr 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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

}

Muthu Dayalan
Newbie Poster
2 posts since Apr 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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--;
zach.hunter
Newbie Poster
1 post since May 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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

stultuske
Industrious Poster
4,372 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 24

Hi this is the solution that i came up with to inverse a string

public static void main(String[] args) {
        // TODO Auto-generated method stub

        String b="bhashitha";

        b.length();
        int p=0;
        String inverse="";
        while(p<b.length()){
        inverse+=b.charAt(b.length()-1-p);

            p++;

        }

        System.out.println(inverse);
    }
bhashitha
Newbie Poster
1 post since Dec 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

bhahista .. that would indeed work, you do have statements you don't use/need, but hey, if it works, it works, right? but anyway, after three years, if the OP hadn't found a way to do it yet, I'm pretty sure (s)he isn't looking anymore.

stultuske
Industrious Poster
4,372 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 24
    StringBuilder sb = new StringBuilder(s3);
    sb.reverse();
    System.out.println(sb);
    s3=sb.toString();
    System.out.println(s3);
gauravbit70
Newbie Poster
1 post since May 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

gauravbit70: allow me to introduce you to a new (still experimental) concept. it's called 'Date'.
you are replying to a thread in which, according to the 'Date' (see how it kicks in?) the last post was almost half a year ago.
that was a post of mine. did you read that? it stated (and I quote)

but anyway, after three years, if the OP hadn't found a way to do it yet, I'm pretty sure (s)he isn't looking anymore.

you want to hear the joke on this? "How to reverse a String" well, actually, you can't. immutable, remember? you just create a new one, the original one won't be reversed anyway.

but still ... my guess is the OP stopped looking for answers about three years ago. maybe we should too.

stultuske
Industrious Poster
4,372 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 24

Hello gauravbit70, welcome to DaniWeb.
Don't be put off by Stultuske, he's just having a bit of fun. Your contributions are very welcome here.
Before posting please do check the dates on threads, and please don't just post solutions with no explanations or comments - we want people to be able to learn from what they read here.
J

JamesCherrill
... trying to help
Moderator
8,516 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,455
Skill Endorsements: 30

Hello. I am aware that this post is outdated, however; I would attempt this problem like so:

package palindrometest;

import java.util.Scanner;

/**
 *
 * @author PBJ
 */
public class PalindromeTest {
    static Scanner console = new Scanner(System.in);  
    public static void main(String[] args) {
        String userInput = getUserInput();
        String reversedInput = reverseUserInput(userInput);
        testForPalindrome(userInput, reversedInput);
    }

    private static String getUserInput() {
        System.out.println("Please enter your String to test");
        String tempString = console.nextLine();
        return tempString;
    }

    private static String reverseUserInput(String userInput) {
        String tempString = new StringBuilder(userInput).reverse().toString();
        System.out.println(tempString);
        return tempString;
    }

    private static void testForPalindrome(String userInput, String reversedInput) {
        if(reversedInput.equals(userInput)){
            System.out.println("Palindrome");
        }
        else{
            System.out.println("Not a palindrome");
        }
    }
}

My version is pretty self explanatory, but I may have misunderstood what I palindrome is. Is it a string that is spelt the same backwards as it is forwards? In that case then I feel that I have addressed the OP's question. If not disregard my attempt, and please don't hurt me

pbj.codez
Newbie Poster
6 posts since May 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

I would say that's a good example of using single-purpose methods methods and well-chosen names. It makes the code so clear that it needs no comments, and it's really easy to read, understand, and verify.

JamesCherrill
... trying to help
Moderator
8,516 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,455
Skill Endorsements: 30

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.1137 seconds using 2.82MB