-1

Team,

I want java program to display string same as it is in reverse order.

Example: Input: I am hulli. Output: hulli am I

Please can help me this program.

Naik Rahul
  • 53
  • 1
  • 1
  • 6

3 Answers3

1

You could split the original string and put it back together by iterating the array from end to start:

String str = "I am hulli";
String[] parts = str.split(" ");
StringBuilder result = new StringBuilder(parts[parts.length - 1]);

// Assume there's at least one world in str
result.append(parts[parts.length - 1]); 
for (int i = parts.length - 2; i >= 0; --i) {
    result.append(" ").append(parts[i]);
}
System.out.println(result);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Here you go

import java.util.*;

class ReverseString
{
   public static void main(String args[])
   {
      String original, reverse = "";
      Scanner in = new Scanner(System.in);

      System.out.println("Enter a string to reverse");
      original = in.nextLine();

      int length = original.length();

      for ( int i = length - 1 ; i >= 0 ; i-- )
         reverse = reverse + original.charAt(i);

      System.out.println("Reverse: "+reverse);
   }
}
Andrew Kralovec
  • 491
  • 4
  • 13
0

You could use on of the many functions prerolled into the Java Collections Framework. Something like this will make use of this function to display the string in reverse order.

String text = "i am hulli";
String[] eachWord = text.split(" ").trim();

List<String> sentence = new ArrayList<>(eachWord.length);

for (int i = 0; i < eachWord.length; i++) {
   sentence.add(eachWord[i]);
}

Collections.reverse(sentence);

for (int i = 0; i < sentence.size(); i++) {
   System.out.print(sentence.get(i) + " ");
}
System.out.println();
andrewdleach
  • 2,458
  • 2
  • 17
  • 25