Alex Rivera | Logout

Join an array of strings in Apex

Asked 2012-02-27T12:46:46.287
20

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?

Edit
Report

1 Answer

30

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
answered 2013-02-28T05:03:19.557

Your Answer