Apex lastindexOf string manipulation

Apex String Manipulation

Apex has several powerful String manipulation features.

You can search for values in Strings, replace matching words, count matching string entries, capitalise letters, remove spaces, and much much more.

There's a good overview of all of the String manipulation methods available here: Apex String methods on Developer Force

On this particular occasion I needed to find the last instance of a few matching characters in a long text field and populate a new field with its value.


lastIndexOf returns the character position of a matching string entry.

For example if you had the words "one two three" and you entered lastindexOf('two') then the script would return 5, as the t of two is 5 characters in from the start.

Once you have found the bit of the String that you need you could then use charAt, LEFT, or RIGHT or another function to bring back the new text that you need.

In my instance the logic I needed was:

  1. Find the position of the last occurence of ACDDelivery~ in the string
  2. Remove all chracters before the matching string using the RIGHT command
  3. Then, as the value I needed was always 25 characers in the remaining string I used LEFT
Here's the final Trigger.

Trigger

trigger FindRingDuration on NVMStatsSF__NVM_Call_Summary__c(before insert) {
     
    //Trigger to extract final ring duration in field NVMStatsSF__Key_Event_String__c
     
    for (Test_Formula__c SS : Trigger.new) {
         
        //SS.Key_Event_String__c
        string abc = SS.NVMStatsSF__Key_Event_String__c;
         
        //Marker for final ring duraion
        Integer intIndex = abc.lastindexOf('ACDDelivery~');
         
        system.debug('### intIndex'+intIndex);
        //Remove all characters before intIndex
        String newString = abc.right(abc.length()-intIndex);
        System.debug(newString);
        //newString is always going to be the last ACD Delivery - lets trim X characters before
        newString = newString.left(25);
        //Actual ring is 25 digits after start of ACDDelivery~
        System.debug(newString);
        newString = newString.right(2);
        System.debug('Ring time is ' + newString);
        //Update the new field
        SS.FinalRingDuration__c = integer.valueOf(newString);
             
    }
     
     
}

Comments