How can I use the Apex string replace method for replacing all occurrences in the Salesforce apex code?
I am a Salesforce developer and I am currently working on a custom apex class for data processing within my organization’s Salesforce instance. In this particular task, I need to manipulate the strings by replacing certain substrings with new values. How can I use the Apex string replace method for replacing all occurrences of a specific substring within a given string with another in the Salesforce apex code?
n the context of Salesforce, here is how you can use the Apex replace method for replacing all occurrence of a specific substring within a given string with another in Salesforce apex code:-
This example would include a method which would task parameters for the original string, the substring to replace, and the replacement substring:-
Public class StringManipulationExample {
// Method to replace all occurrences of a substring in a string
Public static String replaceSubstring(String originalString, String substringToReplace, String replacementString) {
// Check if the originalString and substringToReplace are not null or empty
If (String.isNotBlank(originalString) && String.isNotBlank(substringToReplace)) {
// Replace all occurrences of substringToReplace with replacementString
Return originalString.replace(substringToReplace, replacementString);
} else {
// Handle null or empty input strings
If (String.isBlank(originalString)) {
System.debug(‘Error: Original string is null or empty.’);
}
If (String.isBlank(substringToReplace)) {
System.debug(‘Error: Substring to replace is null or empty.’);
}
// Return originalString if either originalString or substringToReplace is null or empty
Return originalString;
}
}
// Example usage in a test method
Public static void testReplaceMethod() {
// Original string
String originalString = ‘This is a sample string with some sample text.’;
// Substring to replace
String substringToReplace = ‘sample’;
// Replacement string
String replacementString = ‘example’;
// Call the replaceSubstring method to replace all occurrences
String modifiedString = replaceSubstring(originalString, substringToReplace, replacementString);
// Print the modified string to debug logs
System.debug(‘Modified String: ‘ + modifiedString);
// Output: ‘This is a example string with some example text.’
}
}