Salesforce Interview Question

How do you reverse the words in a string? Code.

Interview Answers

Anonymous

Oct 29, 2010

How about pushing the string on a stack (word by word) ignoring the space character and popping the contents of the stack ?

3

Anonymous

Nov 7, 2009

I used the String.split() function here: public static String reverseWords1(String sentence) { // Split string at word separators into string and then output from end. String[] words = sentence.split(" "); StringBuilder result = new StringBuilder(); for(int i=words.length-1; i>=0; i--) result.append(words[i]).append(" "); return result.toString(); } and here by doing it more the traditional way: public static String reverseWords2(String sentence) { StringBuilder result = new StringBuilder(); int lastwordend = sentence.length()-1; for (int i = sentence.length()-1; i>=0; i--) if (sentence.charAt(i) == ' ') { result.append(sentence.substring(i+1, lastwordend+1)+" "); lastwordend = i-1; } return result.toString(); } Go backwards through the sentence, looking for delimiters (i.e. space) and collect the word until you find one or run out of string.

1

Anonymous

Nov 7, 2009

private static String reverse(String s){ if(s == null || s.length() == 1) return s; String rvrsd = reverse(s.substring(1)) + s.charAt(0); return rvrsd; }

3

Anonymous

Aug 21, 2012

There are 2 solutions to this problem. Note that the string is not printed backwards but the words are just printed in reverse order. First is to push each word of the string onto a stack and then pop them off and print them. The second solution requires no extra data structures or space. Simply reverse each word in the string (i.e. scan until you hit a space and then start swapping the first and last letters, moving the pointers toward the center of the word until you meet - then repeat for each word). Then once the words are reversed in the string reverse the entire string and you will get the same result as the first solution.

1

Anonymous

Feb 8, 2015

System.debug('My text is here!'.reverse());

Anonymous

Mar 20, 2016

String reverse(String s) { if(s == null || s.length() == 0) return s; char[] sArray = s.toCharArray(); int l = 0, r = sArray.length - 1; while(l < r) { swap(sArray, l, r); l++; r--; } StringBuilder sb = new StringBuilder(); for(char ch : sArray) sb.append(ch); return sb.toString(); } void swap(char[] sArray, int l, int r) { char temp = sArray[l]; sArray[l] = sArray[r]; sArray[r] = temp; }

Anonymous

Apr 18, 2010

It's also possible to use a BreakIterator to break at word boundaries. That way, it can also work in multiple languages, for the win :-)

Anonymous

May 28, 2012

I used perl my $orgstr="My name is abc"; print "The orignal sentence is: $orgstr\n"; my @tokens= split(' ', $orgstr); my $revstr; foreach my $val (@tokens){ $revstr= $val . ' ' . $revstr; } print "The reversed sentence is: $revstr\n";