4

Following is a string:

 'First Name','Last Name','Account Name','Email','Title','Description'

and I want it to split with ",'" (comma and single quotation mark).

2 Answers 2

4

Try with this

First remove all single quotes and then split by comma

String str = '\'First Name\',\'Last Name\',\'Account Name\',\'Email\',\'Title\',\'Description\'';
System.debug('===str==='+str);
for(String strFinal: str.replace('\'', '').split(','))
{
    System.debug('===Final val==='+strFinal);
}

enter image description here

Another option

If we are sure single quotes will be start and end of string then we can remove using string method

for(String strFinal: str.split(','))
{
    System.debug('===Final val==='+strFinal.removeStart('\'').removeEnd('\''));
}
6
  • I put minus here cause in this case expected result would be received without single quote in the end of each string (after splitting), and in case if of another string with comma in between quote/comma sequences would create extra strings.
    – kurunve
    Apr 11, 2016 at 14:05
  • @kurunve yeah agree.. do you have any idea.. in that use case how we should handle?
    – Ratan Paul
    Apr 11, 2016 at 14:18
  • actually, topic starter proposed one good way about how to do it -- split via ',\''. That would give exactly that outcome that has been asked in question, and it does not have any data loss (in string). Of course, that is pretty easy to do further processing by removing extra quotes if needed. but again -- there would be no data loss or no extra string created
    – kurunve
    Apr 11, 2016 at 14:22
  • @kurunve if you use split(',\'') then this will not give the correct output(I have tested, this contain single quotes end of string).. One more solution I have added in my answer check..
    – Ratan Paul
    Apr 11, 2016 at 14:26
  • @ sfdcweb, it you test your both ways on string "\'Test, string\',\'test, so test\'', those would fail. There is nowhere asked to have those values with/without quotes. Just question about how to split. again, split on ',\'' would do the magic, and then, if needed, you can remove extra quotes from begin and end. Splitting just on comma would produce extra string and make wrong output
    – kurunve
    Apr 11, 2016 at 14:35
1

I tried following code and it works fine.

String str = '\'First Name\',\'Last Name\',\'Account Name\',\'Email\',\'Title\',\'Description\'';

List<String> splitList = str.split(',\'');

for(String str : splitList)
    System.debug(str.replace('\'',''));
3
  • 1
    Dilip... this ans will give you text with single quotes..
    – Ratan Paul
    Apr 11, 2016 at 14:27
  • Finally you removed the single quotes.. You are looking for only text string. Thanks for update your answer.. This is the same thing I did yesterday..
    – Ratan Paul
    Apr 12, 2016 at 7:25
  • 1
    hmmm..... right. Apr 12, 2016 at 7:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .