Join an array of strings in Apex

Kp Gupta picture Kp Gupta · Feb 27, 2012 · Viewed 24.8k times · Source

Using Apex, I want to split a string and then rejoin it with the 'AND' operator as the separator.

I split the string successfully but having an issue in rejoining it.

 String [] ideaSearchText = searchText.Split(' ');
 // How to rejoin the array of strings with 'AND'?

How can I do this?

Answer

doublesharp picture doublesharp · Feb 28, 2013

You can do this as of v26 (Winter 13) by passing your String[] to String.join().

String input = 'valueOne valueTwo valueThree';
String[] values = input.split(' ');
String result = String.join( values, ' AND ' );

Anonymous Apex output calling System.debug(result):

21:02:32.039 (39470000)|EXECUTION_STARTED
21:02:32.039 (39485000)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
21:02:32.040 (40123000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|<init>()
21:02:32.040 (40157000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|<init>()
21:02:32.040 (40580000)|USER_DEBUG|[5]|DEBUG|valueOne AND valueTwo AND valueThree

Salesforce API Documentation: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm