4

I have a string where I want to replace all of the spaces with plus (+) symbols.

I've tried a number of different ways but the debug log is always showing that nothing is being replaced

I'm passing in a = 101 e wilson st c = madison z = 53703

the end result should be: 101+e+wilson+st+madison+53703

However it's coming out as: 101 e wilson st+madison+53703

string param = a + '+' + c + '+' + z; So the replace all Regex is not working.

Apex:

  public void getCoord(string a, string c, string z){
            Http h = new Http();
            HttpRequest req = new HttpRequest();

            a.replaceAll('\\s+', '-');
            c.replaceAll('\\s+', '-');
            z.replaceAll('\\s+', '-');

            string param = a + '+' + c + '+' + z;
            system.debug('looking for coordinates');
            req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address='+ param +'&sensor=false');
1

2 Answers 2

10

The replaceAll method returns the modified string, it does not modify the reference to the value passed.

So you should change it to this and it should work for you:

a = a.replaceAll('\\s+', '-');
c = c.replaceAll('\\s+', '-');
z = z.replaceAll('\\s+', '-');
1
  • this worked perfect
    – tjcinnamon
    Commented Aug 1, 2016 at 16:30
6

Eric has a good answer, but this will also work for this specific case, just a generic method for what you're trying to do, this will return a working format for POST to google

public static String buildAddressForGooglePost(String street, String city, String state, String postalCode, String country)
{
    String result = '';

    if (street != null) result += street +', ';
    if (city != null) result += city +', ';
    if (state != null) result += state +' ';
    if (postalCode != null) result += postalCode +', ';
    if (country != null) result += country;

    result = EncodingUtil.urlEncode(result, 'UTF-8');

    return result;
}
3
  • 2
    You could also just do a List<String> with a , join. Bit cleaner IMO.
    – Adrian Larson
    Commented Jul 29, 2016 at 4:17
  • Yup for sure, I agree..
    – EricSSH
    Commented Jul 29, 2016 at 4:59
  • @AdrianLarson how would I do that?
    – tjcinnamon
    Commented Jul 29, 2016 at 21:22

You must log in to answer this question.

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