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

split text in salesforce

How can we split street field into two different fields via Apex coding.

I know there is a way to do it through split method dividing using delimiters ex:
String s1 = 'Hello Max wrwer 345345';
//String s2 = s1.left(3);
List<String> s3 = s1.split(' ',2);
//List<String> s3 = s1.split('\n');


But How can we split on the basis of Number of characters for example Before 8th character it should store in field1 and after 8th to 30th character in field 2 and so on ....

Could you please help me here
Jayant JadhavJayant Jadhav
Hi Ashishyadav,

You can use substring function to split based on number of charaters.


'hamburger'.substring(4, 8); // Returns "urge"  'smiles'.substring(1, 5); // Returns "mile" 

Dushyant SonwarDushyant Sonwar
Hi Ashish,

You can also use left(integer) and right(integer) , mid(startIndex, length) method of string class to achieve your output.
See this.
Amit Chaudhary 8Amit Chaudhary 8
Try code link below :-
public String removePath(String filename) {
        if (filename == null)
            return null;
        List<String> parts = filename.split('\\\\');
        filename = parts[parts.size()-1];
        return filename;

    static testMethod void testRemovePath() {

Please see all String method in below link

For example, for String s = 'boo:and:foo':s.split(':', 2) results in {'boo', 'and:foo'}
s.split(':', 5) results in {'boo', 'and', 'foo'}
s.split(':', -2) results in {'boo', 'and', 'foo'}
s.split('o', 5) results in {'b', '', ':and:f', '', ''}
s.split('o', -2) results in {'b', '', ':and:f', '', ''}
s.split('o', 0) results in {'b', '', ':and:f'}

Please let us know if this will help you


Thanks @Amit, I have already referred that , it does not help much when number of characters comes into act.

@Dushyant Sonwar : I havent tried that yet,

@Jayant Jadhav: Thanks es , that what I was trying earlier , but there is one condition if length of string is 100 charachers and Iam doing something like this

   address1 =spliting[1].substring(0,70);
   address2 =spliting[1].substring(71,150);

It will throw an error as number of characters is 100 only : System.StringException: Ending position out of bounds: 150   

Jayant JadhavJayant Jadhav

Ok, Then we can use if statement to avoid this exception. Try below code.
public class StringSubstring 
	public static void checkString(String input)
        String Address1='';
        String Address2='';
        if(input!=null && input!='' && input.length() >70)
        else  if(input!=null && input!='' && input.length() <= 70)
        System.debug('Address 1 '+Address1);
        System.debug('Address 2 '+Address2);

Let me know if this works for you.