Skip to main content
Could someone please explain how the .split method works in a String?

I am facing this line in a code:

String domain = myContact.Email.split('@').get(1);

I believe it is trying to capture the domain of an email address (and assign it to the variable

domain), so if the email address is, for example: firstName.LastName@salesforce.com, the above line of code is probably capturing the domain 'salesforce.com' and assigns it to the variable.

But how does it do it? How does this .split method works= I do not understand this bit: .split('@').get(1);

When looking at Salesforce String methods here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm , and searching by .split, I find the following method/description:

string method

so, even if I do not understand how could this method possibly return a "list", I sort of guess that it returns a substring that is terminated by a regular expression that, in my line of code would be '@' ? But, this does not make sense in my line of code as the substring in it that terminates with '@' would in fact be firstName.LastName (not salesforce.com). 

Also, what is the .get(1) doing in this line of code?

Thank you very much.
7 Antworten
  1. 7. Nov. 2017, 14:06

    Hi,

    It is used to break your string. Showing an example below with a small case about it. May be this can help you. 

    Example: 

    Let suppose you are getting somethig like address(F-206, Daffodils, Magarpatta, Pune, India, 411028) in one text field and you want to store this address in different segments like house no, Building name, Street, City, Country. for this you can use split function for this by given code. 

    String addressFull  = 'F-206, Daffodils, Magarpatta, Pune, India, 411028';

    String[] address     = addressFull.split(',');

    String houseNumber         =     address[0]; 

    String buildingName          =    address[1];

    String streetName             =    address[2];

    String cityName                 =    address[3];

    String countryName           =    address[4];

    System.debug(houseNumber);

    System.debug(buildingName);

    System.debug(streetName);

    System.debug(cityName);

    System.debug(countryName);

     

    Output: please check debug logs after that, you will be able to see