Context
- I have five fields of fixed lengths that add up to 255 characters.
- Lets call them
split1
,split2
,split3
,split4
,split5
- split1 -> max 80 characters
- split2 -> max 60 characters
- split3 -> max 40 characters
- split4 -> max 40 characters
- split5 -> max 35 characters length
- We have a field with a max character size of 255, lets call this
myStr
Goals
- Split the
myStr
field into the 5 split fields based on the closest whitespace - while splitting, we don't want to cut the string in the middle of a word
What I tried
String str = 'Aliquip nisi Duis incididunt minim, cupidatat, est id culpa. Mollit cupidatat, officia do tempor ex amet. Fugiat sint Excepteur Duis. Nostrud consectetur occaecat ea commodo, lorem, esse officia sunt. Dolore ullamco adipiscing sed.';
List<String> listStr = new List<String>{
str.substring(0, Math.min(80, str.length())),
str.substring(80, Math.min(80, str.length())),
str.substring(140, Math.min(140, str.length())),
str.substring(180, Math.min(180, str.length())),
str.substring(220, Math.min(220, str.length()))
};
System.debug('Str: ' + JSON.serializePretty(listStr));
System.debug('Str length: ' + str.length());
Current Output
[ "Aliquip nisi Duis incididunt minim, cupidatat, est id culpa. Mollit cupidatat, o", "", "", "", "" ]
Expected Output
[ "Aliquip nisi Duis incididunt minim, cupidatat, est id culpa. Mollit cupidatat, ", " officia do tempor ex amet. Fugiat sint Excepteur Duis. ", "Nostrud consectetur occaecat ea commodo,", "lorem, esse officia sunt. Dolore ullamco", " adipiscing sed." ]
Where i need help
- how do i get to split based on the max character lenth of each field?
String.lastIndexOf
) in the required run of characters length; if you find one, split there. If you don't the best you can do is split the long word at the maximum length you need. You then remove this part of the string and process the remainder with the next required run of characters length and so on. NB: chat GPT gives a fair answer if you also tell it you want the code to be Salesforce Apex.