Activity Forums Salesforce® Discussions Accidently splitting an empty string on some specific character returns a list of size One

  • Accidently splitting an empty string on some specific character returns a list of size One

    Posted by Utsav on March 23, 2016 at 6:41 am

    Why splitting of empty string on some specific character returns a list of size One? What does this list contain if it has size One?
    Sample code:

    `string s='';
    list<string> str = s.split(',');
    if(str.isEmpty()){
    system.debug('Hello i am empty');
    }
    else{
    system.debug('oops');
    }

    Shubham replied 8 years, 8 months ago 4 Members · 3 Replies
  • 3 Replies
  • Akash

    Member
    March 23, 2016 at 7:00 am

    The property of split() is such that the list you get back always has at least one element. You are splitting the empty string, and so you're getting back a list of size 1, where the element in the list is the empty string.

  • Ravi

    Member
    March 23, 2016 at 7:01 am

    Splitting an empty string returns the empty string as the first element. If no delimiter is found in the target string, you will get an array of size 1 that is holding the original string, even if it is empty
    Example:
    String str =",Utsav"
    str.split(',') will return a list of size 2

    If you split an orange zero times, you have exactly one piece - the orange

    • This reply was modified 8 years, 8 months ago by  Ravi.
  • Shubham

    Member
    March 23, 2016 at 7:41 am

    Split always returns at least one element.
    In the case that a separator is not found, the entire input (empty String) is returned as a single-element in the List. For that reason the List size will be always one.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos