2

Hi I am trying to reverse a String to make a palindrome. Can someone please give me a tutorial on how to reverse a string? I have read some tutorials online and I have tried applying them to the palindrome program that i am writing but have not been successful.

import java.util.Random;

public class IterativePalindromGenerator {

    public static void main(String[] args) {

        Random random = new Random();

        int floorValue = 1;

        int cielingValue = 20;

        int randomNumber = random.nextInt(cielingValue - floorValue)
                + floorValue;

        String alphabetLetters = "abcdefghijklmnopqrstuvwxyz";

        for (int i = 0; i < randomNumber; i++) {

            char generatedLetters = alphabetLetters.charAt(random
                    .nextInt(alphabetLetters.length()));

            String generatedLetterSTRINGType = Character
                    .toString(generatedLetters);// converts char to string

            System.out.print(generatedLetterSTRINGType);

        }   
    }

}
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139

3 Answers3

2

To reverse a string you can use StringBuffers reverse() method:

public String reverse(String stringToReverse) {
    return new StringBuffer(stringToReverse).reverse().toString();
}
benbjo
  • 2,382
  • 3
  • 18
  • 21
1

Hey here is my code from a college course. Our task was to implement a recursive procedure. Hope this can help the community.

package DiskreteMathe;
import java.util.*;

public class AufgabePalindromTestRekursiv {

    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);     
        System.out.println("Please enter text here:");
        String text= sc.next();
        System.out.println(testPalindrom(text));
    }
    public static boolean testPalindrom (String text){
        if (text.length()==2 && text.charAt(0)==text.charAt(1) || text.length()==1)
            return true;
        if(text.charAt(0)!=text.charAt(text.length()-1)){
            return false;
        } else {
            text = text.substring(1, text.length()-1);
            return testPalindrom(text);
        }
    } 
}
Nik Las
  • 11
  • 1
0

When creating a palindrome for existing string, you need to think of the cases of even and odd outcome strings. For example, if you input String "abc", you should expect there are two outcome palindrome strings: abccba (even) and abcba (odd).

Here is my code:

public class PalindromeGenerator {

public static void main(String[] args) {
    String str = "abc";
    String reverse_str = "";


    for (int n = str.length(); n>0; n--){
        reverse_str += str.substring(n-1, n);
    }

    String even_str = str + reverse_str;
    String odd_str = str.substring(0, str.length()-1) + reverse_str;

    System.out.println(even_str); // print "abccba"
    System.out.println(odd_str); //print "abcba"
}

}

I Hope this can help you.

mlchen850622
  • 668
  • 6
  • 7