I am not getting why It is not giving me the correct output. If i Test 0011b00000sXK8mAAG id then result is YES or if i test any id from (0011b00000sXKBgAAO / 0011b00000sXKgDAAW ) then it gives me No output. i am not getting what is the problem. and how can i fix that issue.

Note: String myid can be dynamic. Here i just use ids for testing purpose .

string myid = '0011b00000sXK8mAAG, 0011b00000sXKBgAAO, 0011b00000sXKgDAAW,';
Set<string> abc = new set<string>();
system.debug('string: ' + myid);
system.debug('set: ' + abc);



enter image description here

1 Answer 1


Your starting string (0011b00000sXK8mAAG, 0011b00000sXKBgAAO, 0011b00000sXKgDAAW,) contains two space characters.

If you split the string on the commas, there is a preceding space character that gets included in the second ( 0011b00000sXKBgAAO) and third ( 0011b00000sXKgDAAW) elements in your list. You will see the spaces if you run the following:

String t = '0011b00000sXK8mAAG, 0011b00000sXKBgAAO, 0011b00000sXKgDAAW,';

Set<String> setOfStrings = new Set<String>(t.split(','));

for(String s : setOfStrings) {

You will need to either 1) start with a string that has no white-space, 2) strip out the white-space characters, or 3) use String.split(', ') with a space so the comma and space as a pair are treated as the string to split on.

My recommendation, if your source string should always be a comma-delimited list of IDs, is to use deleteWhitespace like so: myString = myString.deleteWhitespace(). That will remove all whitespace characters from your string.

  • Thank you so much, Great. Oct 2, 2020 at 19:08
  • 1
    Also: Ids should be stored in a Set<Id>, not a Set<String>. Strings don't know that 15-char == 18-char Id, and don't validate for legal Ids.
    – David Reed
    Oct 2, 2020 at 19:09

You must log in to answer this question.

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