I'm attempting to remove the store from my referral store number and was curious if anyone had any experience trimming anything after a space in a variable. For example I have a variable that equals Chicago 1111. I want to be able to automatically trim chicago off of the variable no matter how long the numbers are.

I currently am trying this.

String Ref = a.Referral_Store__c;

  if (a.Referral_Store__c != null) {
 Ref = a.Referral_Store__c.substringAfter(' ');

However I'm getting the error

caused by: System.NullPointerException: Attempt to de-reference a null object

  • 1
    What have you tried so far? Please edit this post to include include any attempts you have made and expected input/output combos. – Adrian Larson Aug 28 '17 at 23:59
  • @AdrianLarson There, I updated my post using your suggestion and revised the order of the city and number as I had typed them in reverse. However, I'm getting a null object error. – Nathan White Aug 29 '17 at 0:43
  • 1
    As written, the only place where you're capable of throwing the null pointer exception is if a is null when you're referencing Referral_Store__c from it. – Mark Pond Aug 29 '17 at 0:47
  • @MarkPond Alright, great, I'll hunt through the code and see what I can find. Possible that it is just above the initiation of a. – Nathan White Aug 29 '17 at 0:48
  • Change your if statement to: if (a!= null && a.Referral_Store__c != null) – Caspar Harmer Aug 29 '17 at 1:01

If you want to remove everything after the first occurrence of a specific character, I recommend using substringBefore:

String beforeFirstSpace = someInput.substringBefore(' ');
| improve this answer | |

A string replace should do the trick:

String s = myString.replace('Chicago','');

You could also try something like this (for case insensitivity):

var endIndex = myString.indexOfIgnoreCase('Chicago');
String s = myString.substring(0, endIndex-1);
| improve this answer | |
  • I think this might just work... I have a variable with each store location and should be able to put that variable where Chicago is and then replace it. Thanks so much, again. I'll let you know what I come up with. – Nathan White Aug 29 '17 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.