function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dipa87Dipa87 

Need help in string formatting function.

I have a string which contains object names enclosed in <>. Like this:

 

                                String str = 'I have <name> and <id>  and <phone>';  //The string may vary,so it needs to be dynamic

 

I need an output like this. So that i can use the field names to use it in my soql query.


                                String fields = 'name,id,phone';   

Best Answer chosen by Admin (Salesforce Developers) 
Dhaval PanchalDhaval Panchal

try this.

 

String str = 'I have <name> and <id>  and <phone>';
List<String> lst = str.split(' ');
String fld = '';
for(String s:lst){
   if(s.contains('<') && s.contains('>')){
      s = s.replace('<','');
      s = s.replace('>','');
      if(fld == ''){
         fld = s;
      }else{
         fld += ',' + s;
      }
   }
}
system.debug('###### String: ' + str);
system.debug('###### fields: ' + fld);

############################################################################################
Its working for me, I got below result in debug.

18:03:42.049 (49353000)|EXECUTION_STARTED
18:03:42.049 (49367000)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
18:03:42.050 (50509000)|USER_DEBUG|[15]|DEBUG|###### String: I have <name> and <id>  and <phone>
18:03:42.050 (50551000)|USER_DEBUG|[16]|DEBUG|###### fields: name,id,phone
18:03:42.050 (50596000)|CODE_UNIT_FINISHED|execute_anonymous_apex
18:03:42.050 (50605000)|EXECUTION_FINISHED