Swift - 如何将 hyphen/minus 符号转换为 + 符号

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


我正在从以下代码的 iOS 反向地理编码中获取字符串变量中的地址。

    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 变量有地址 - "2362-2658 W 12th St\nCity, State 20301\nCountry Name"

我需要在 tmpAddress 变量中将 2362-2658 更改为 2362+2658,但我无法通过

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

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

有人可以建议为什么上面的 stringByReplacingOccurrencesOfString 不起作用以及如何实现。

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

这会将“-”替换为“+”

第一个参数是搜索字符串,第二个参数是替换字符串。

尝试这样的事情:

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))

或简化:

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

您的问题是您将空的 space“ ”替换为“-”。在您的原始代码中不是带“+”的“-”。