0

I am trying check below string in the if condition but apparently it is not satisfying the string comparison condition even though system.debug shows the same string.

 String APH = test.substring(0,3);
 system.debug('inside APH '+ APH ); // outputs A&P
 if(APH == 'A&P '){
 system.debug('after substring '); // not printing
 }

I have even tried to do this but still not working

if(APH == 'A\\&P '){ 

1 Answer 1

1

Your comparison has an extra whitespace after the string you're actually looking for

'A&P ' is the problem, it should be 'A&P'

That said, you could probably make whatever it is you're trying to do simpler (and more reliable) by simply using String.contains().

e.g. if(test.contains('A&P')){ // do work }

4
  • well that whitespace was intentional but anyway your contains() suggestion turns out to be working fine.
    – Akash
    Jan 22, 2021 at 15:41
  • @Akash substring(0,3) would return a string of length 3 (zero indexed, and it stops at endIndex - 1), so comparing it to a string of length 4 will obviously never return true.
    – Derek F
    Jan 22, 2021 at 15:46
  • m confused, how is it 4 ? A-0,&-1,P-2, -3. Am I Correct? I was trying intentionally compare 'A&P ' with 'A&P ' from the substringed variable. correct me if I am wrong
    – Akash
    Jan 22, 2021 at 15:49
  • 1
    @Akash Like I said, substring(0, 3) returns indexes 0-2 (end index is 3, the documentation says the result is from the start index to end index - 1). Your given substring() call returns a string of length 3, not 4. You can check that for yourself by using system.debug(APH.length()); 'A&P ' is a length of 4. Strings of different lengths will never be equal.
    – Derek F
    Jan 22, 2021 at 15:53

You must log in to answer this question.

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