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
Siddharth ManiSiddharth Mani 

Remove a character from String and store the remaining in a list

Hi,

Suppose I have a String like this:
String myString = ';abc;;;def;;ghi;jkl;lmnop';

Is it possible to create a list like {abc,def,ghi,jkl,lmnop} ??
Basically the values will be separated by semicolon, but it might not be a single one and it may also occur at the start and end. I want only the values stored in a separate list
Best Answer chosen by Siddharth Mani
Amit Chaudhary 8Amit Chaudhary 8
Please try below code. I hope that will help you :-
String myString = ';abc;;;def;;ghi;jkl;lmnop';
List<String> NewList = myString.split(';');
List<String> myList = new List<String>();
For(String str : NewList)
{
  if(str!='')
  {
   mylist.add(str);
  }
}
System.debug('------------------>'+mylist);

Output will be
------------------>(abc, def, ghi, jkl, lmnop)

 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please check below post all string function
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm
 
String myString = ';abc;;;def;;ghi;jkl;lmnop';
String s2 =  myString .remove(';');
System.debug('---------------->'+s2);
you can also try replace(target, replacement)

 
Siddharth ManiSiddharth Mani
I guess I didnt update the question properly. I dont just want to remove the semicolon and make it a whole String - the semicolon is supposed to be a delimiter and so the output which I need is a list of the individual components SEPARATED by the semicolon. But the string is messed up with multiple delimiters appearing at the start and end and also in between. So I was asking if there is a way to achive what I had posted as an output:

{abc,def,ghi,jkl,lmnop}   ----------> This should be the output list with each item being a separate element.

For eg. if "myList" is the variable which contains the output then:
myList[0] = abc
myList[1] = def ..................and so on

Hope its clear now!!
Amit Chaudhary 8Amit Chaudhary 8
Please try below code. I hope that will help you :-
String myString = ';abc;;;def;;ghi;jkl;lmnop';
List<String> NewList = myString.split(';');
List<String> myList = new List<String>();
For(String str : NewList)
{
  if(str!='')
  {
   mylist.add(str);
  }
}
System.debug('------------------>'+mylist);

Output will be
------------------>(abc, def, ghi, jkl, lmnop)

 
This was selected as the best answer
Siddharth ManiSiddharth Mani
Thank you.. That is what I needed!