0

how to reverse text

public class Yoda { public static void main(String[] args) { // sample text String text = "I am your Father "; String result = reverseWords(text); System.out.println(result); } static String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } // split words String[] arr = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = arr.length - 1; i >= 0; --i) { if (!arr[i].equals("")) { sb.append(arr[i]).append(" "); } } return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1); } } // i see how this says father your am i //but how do i get it to say rethaf ruoy ma i ?

18th Oct 2016, 1:02 PM
Aquarius
Aquarius - avatar
5 Respostas
+ 3
#include <iostream> #include <string> using namespace std; string reverseStr(string x) { string temp = ""; int len = x.length(); for (int i = len - 1; i >= 0; --i) { temp += x[i]; } return temp; } int main() { //sample text string text = "YOURSTRING"; cout << reverseStr(text); return 0; }
16th Nov 2016, 11:17 AM
Ziyaan Hassan
Ziyaan Hassan - avatar
+ 2
why don't you use another string and then start putting each character from starting of 1st string (char array) to 2nd string' s opposite end or use swap using temP character variable
18th Oct 2016, 1:45 PM
Rajeev Ranjan
Rajeev Ranjan - avatar
+ 2
I understand you doing your own method for it but you'd rather use the built in StringBuilder/StringBuffer reverse method and then convert it back to String.
18th Oct 2016, 7:12 PM
Ousmane Diaw
+ 1
thank you for both your answers
18th Oct 2016, 10:11 PM
Aquarius
Aquarius - avatar
+ 1
u may use collection interface and Collections class it has reverse method
20th Oct 2016, 12:01 PM
Ankur Sharma
Ankur Sharma - avatar