[SalesForce] How to remove text field value after comma using apex code

I have text field and that field has these two email address, field value is look like abc@test.com, def@test.com

Now, i need to remove second email address after comma..

i wrote some code to achieve this, can somebody please tell me about the mistake in this code :

if(a.Temporary_Email_address_coming_from_OTT__c != null){
     List<String> tempstr = String.valueOf(a.Temporary_Email_address_coming_from_OTT__c).split(',');
     system.debug('++++tempstr++++++'+tempstr);
     String temp = '';
     for(string str : tempstr){
          if(Str.trim().length() > 0){
          temp = temp+str;
          system.debug('++++temp1++++++'+temp);
     }
     a.Temporary_Email_address_coming_from_OTT__c = temp.removeEnd(',');
     system.debug('++++Temporary_Email_address_coming_from_OTT__c++++++'+a.Temporary_Email_address_coming_from_OTT__c);

}

Please suggest !!

Thanks a lot 🙂

Best Answer

if you only need the first email value,you don't need any loop.
Just use the code below;

if(a.Temporary_Email_address_coming_from_OTT__c != null && (a.Temporary_Email_address_coming_from_OTT__c).contains(',')){
    a.Temporary_Email_address_coming_from_OTT__c = a.Temporary_Email_address_coming_from_OTT__c.split(',')[0];
}
Related Topic