function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ronmisronmis 

Split String without spaces into multiple strings

I've got a string like so "The_quick_brown_fox_jumps_over_the_lazy_dog"

I want to add a space every 10 characters to it only if those 10 characters don't alreay have a space

so I'm hoping for a result like this
"The_quick_ brown_fox_ jumps_over _the_lazy_ dog"

But if the String was this
"The quick brown fox jumps over the lazy dog"
then it should remain the same.
Best Answer chosen by ronmis
Nayana KNayana K
public String addSpaceAfter10chars(String mainString) {

	if(String.isBlank(mainString) || (String.isNotBlank(mainString) && mainString.containsWhiteSpace())) {
		return mainString;
	}
	String extendString = '';
	String temp = mainString;
	String temp2 = '';
	while(temp.length() >= 10) {
		temp2 = temp.substring(0,10);
		extendString += temp2 + ' ';
		temp = temp.removeStart(temp2);
	}

	extendString += temp;
	/*below line is optional. If you don't want the space at the end of the new string*/
	extendString = extendString.removeEnd(' ');
	system.debug('===extendString==='+extendString);
	return extendString;
}

Invocations: 
addSpaceAfter10chars('The quick_brown_fox_jumps_over_the_lazy_dog'); // returns The quick_brown_fox_jumps_over_the_lazy_dog

addSpaceAfter10chars('The_quick_brown_fox_jumps_over_the_lazy_dog'); // returns The_quick_ brown_fox_ jumps_over _the_lazy_ dog

addSpaceAfter10chars(null); // returns null