Join an array of strings in Apex
Asked Answered
M

2

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?

Mott answered 27/2, 2012 at 12:46 Comment(0)
C
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
Chloral answered 28/2, 2013 at 5:3 Comment(2)
Thanks very much for this answer. It has helped me get out of deep waters. Moreover, it really makes sense and makes me better understand what implementation choices increase the heap size.Legislative
Note, it seems you can't join a Set<String> -- any suggestions (besides converting it to a list)?Ailment
G
0

Note if the string object is too large you will get the exception Regex too complicated. In this case you can do something like the following:

Blob blobValue = (Blob)record.get(blobField);

// Truncate string then split on newline, limiting to 11 entries
List<String> preview = blobValue.toString().substring(0,1000).split('\n', 11);

// Remove the last entry, because The list’s last entry contains all 
// input beyond the last matched delimiter.
preview.remove(preview.size()-1);

// In my use-case, I needed to return a string, and String.join() works 
// as the reverse of split()    
return String.join(preview, '\n');
Gypsophila answered 19/10, 2018 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.