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