Swift - how to convert hyphen/minus sign into + sign

532 Views Asked by At

I am obtaining address in string variable from iOS reverse geocoding from below code.

    CLGeocoder().reverseGeocodeLocation(imageLocation, completionHandler:
                    {(placemarks, error) in
      dispatch_async(dispatch_get_main_queue(), {                            
 if (error != nil) {println("reverse geodcode fail: \(error.localizedDescription)")
      textField.placeholder = "Address not found."              
     }
 else
    {
 if placemarks.count > 0
    {
var placemark:CLPlacemark = placemarks[0] as! CLPlacemark     
var locationAddress:NSArray = placemark.addressDictionary["FormattedAddressLines"]   as! NSArray
 var tmpAddress = locationAddress.componentsJoinedByString("\n")
 textField.text = tmpAddress as String
                                }
                            }
                        })
                })

tmpAddress variable has address - "2362-2658 W 12th St\nCity, State 20301\nCountry Name"

I need to change 2362-2658 into 2362+2658 in tmpAddress variable but i am not able to do so by

tmpAddress = tmpAddress.stringByReplacingOccurrencesOfString("-", withString: "+")

or

tmpAddress = tmpAddress.stringByReplacingOccurrencesOfString("\u{2212}", withString: " ")

Please can someone suggest why stringByReplacingOccurrencesOfString above is not working and how can this be accomplished.

2

There are 2 best solutions below

2
On BEST ANSWER

tmpAddress = tmpAddress.stringByReplacingOccurrencesOfString("-", withString: "+")

This replaces '-' with '+'

The first parameter is the search string, and the second is the replacement string.

2
On

Try something like this:

var str =  "2362-2658 W 12th St\nCity, State 20301\nCountry Name"
var start = str.startIndex
var end = advance(start, str.characters.count)
var modStr = str .stringByReplacingOccurrencesOfString("-", withString: "+", options:.CaseInsensitiveSearch, range: Range<String.Index>(start: start, end: end))

Or simplified:

var modStr = str .stringByReplacingOccurrencesOfString("-", withString: "+")

Your issue is you are replacing an empty space " ", with a "-". Not a "-" with "+" in your original code.