2

I'm attempting to replace a portion of a large text area using the code below without success. Have I misunderstood the proper usage of the string replace method, and if so, is there another methodology I should be using instead? I'll add that I've verified that the data is valid.

for(Event ev:Evt){
    Descrip = ev.Description;
    // oEvtOwners is a map of WhatID to the old OwnerID
    // nEvtOwners is a map of WhatID to new OwnerID

    system.debug(string.valueOf(oEvtOwnrs.get(ev.WhatID)); // old event owner name

    system.debug(string.valueOf(nEvtOwnrs.get(ev.WhatID)); // new event owner name

    system.debug(Descrip.contains(string.valueOf(oEvtOwnrs.get(ev.WhatID)))==true);

    if(Descrip.contains(string.valueOf(oEvtOwnrs.get(ev.WhatID)))==true){

       Descrip.replace(string.valueOf(oEvtOwnrs.get(ev.WhatID))), string.valueOf(nEvtOwnrs.get(ev.WhatID)));

       /* if true, replace old owner string with new owner string anyplace in Descrip */

    }

    system.debug(Descrip); // old owner is still there, not the new owner!!!

    ev.Description = Descrip;

    ev.OwnerID = nEvtOwnrs.get(ev.WhatID); // new owner applied as expected!!!  

    Evnt.add(ev);            

    } // end for e:Evt

update Evnt;

As you can see from the comments in the code, the old ownerID is being updated to the new ownerID just before the update is performed, but the string code isn't updating the Description string/textArea from what I'm seeing in the debug logs.

This is happening even though the old owner and the new owner values along with the Descrip.contains are all evaluating properly in the system.debug statements. As such, I don't understand why the Descrip.replace(oldstring,newstring) isn't working! Any insights or suggestions?

9

Strings are immutable which means that they cannot be modified. When you call an instance operation on a String it creates a new String instance to return.

You need to assign the result to another variable (or to the variable itself).

For example:

Descrip = Descrip.replace(string.valueOf(oEvtOwnrs.get(ev.WhatID))), string.valueOf(nEvtOwnrs.get(ev.WhatID)));
|improve this answer|||||
  • Sometimes it really annoys me when the docs are incomplete (there was no example code for syntax on the use of replace in the Apex docs)! Since the code was being accepted by Eclipse & the SF Servers, I incorrectly "assumed" this method was like other instance methods that don't need assignment. Thanks Peter! VERY helpful info!:) – crmprogdev Jul 8 '13 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.