[SalesForce] Substring Error – Ending Position Out Of Bounds

I am trying to copy a Rich Text Field (32k) into multiple Rich Text Field (2k). I get this error:

System.StringException: Ending position out of bounds:2000.

Code

trigger UpdateCaseResponse on Case (before update) {
    for(Case c: trigger.new ){
        if (c.Response__c != null)        
        if(c.Response__c != Trigger.oldMap.get(c.Id).Response__c )

        try{
            c.Response_Part1__c = c.Response__c.substring(0,2000);
            c.Response_Part2__c = c.Response__c.substring(2001,4000);
        }       
        catch (System.NullPointerException e) {


        }
    }
}

Best Answer

As an alternative to using substring, you can also use Pattern/Matcher:

SObjectField[] fields = new SObjectField[] {  // List your fields...
    Case.Response_Part1__c, Case.Response_Part2__c,
    Case.Response_Part3__c, Case.Response_Part4__c // ...
};
Pattern p = Pattern.compile('(?s).{1,2000}');  // Read up to 2k at a time

for(Case record: Trigger.new) {
    if(record.Response__c == null || record.Response__c == Trigger.oldMap.get(record.Id).Response__c) {
        continue;
    }
    Matcher m = p.matcher(c.Response__c);
    for(Integer fieldToUse = 0; fieldToUse < fields.size() && m.find(); fieldToUse++) {
        record.put(fields[fieldToUse], m.group(0));
    }
}

This avoids substring exceptions and a particularly nasty set of if statements.

Related Topic