Salesforce.com Interview Question
144 Interview Reviews |
Back to all Salesforce.com Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Salesforce.com:
How do you reverse the words in a string? Code.
See more for this Salesforce.com Software Engineer Interview
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (5)
2 of 3 people found this helpful
if(s == null || s.length() == 1) return s;
String rvrsd = reverse(s.substring(1)) + s.charAt(0);
return rvrsd;
}
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
3 of 3 people found this helpful
Helpful Answer?
Yes |
No
Inappropriate?
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";
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
1 of 1 people found this helpful
by Martin:
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.