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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Kp Gupta
  • 483
  • 2
  • 7
  • 23

2 Answers2

29

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
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • 1
    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. – altius_rup Oct 30 '16 at 13:50
  • Note, it seems you can't join a Set -- any suggestions (besides converting it to a list)? – Kimball Robinson Feb 26 '19 at 18:33
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');
isherwood
  • 58,414
  • 16
  • 114
  • 157
Shanerk
  • 5,175
  • 2
  • 40
  • 36