Write a Salesforce apex Program to Reverse a Sentence.
- Abhilash Banpurkar
- Jan 20, 2023
- 1 min read
Here is an example of a Salesforce Apex program that takes a sentence as input and reverses the order of the words:
public class ReverseSentence {
public static String reverseWords(String sentence) {
String[] words = sentence.split(' ');
String reversedSentence = '';
for (Integer i = words.size() - 1; i >= 0; i--) {
reversedSentence += words[i] + ' ';
}
return reversedSentence.trim();
}
}
This code defines a class ReverseSentence with a static method reverseWords(). The method takes a string (sentence) as input. The split(' ') method is used to split the sentence into an array of words. Then the code loops through the array of words in reverse order and appends each word to the reversedSentence variable. The trim() method is used to remove any extra spaces at the end of the reversed sentence. Here is an example of how you can use the reverseWords() method:
You can also use it to reverse a sentence in a Visualforce page or a controller method.
Execution Part:
String originalSentence = 'The quick brown fox';
String reversedSentence = ReverseSentence.reverseWords(originalSentence);
System.debug(reversedSentence);
OUTPUT:
This will output:
fox brown quick The
Comentários