removing white spaces at beginning and end of string

前端 未结 8 1110
天涯浪人
天涯浪人 2021-01-14 01:41

I\'ve got a problem with removing whitespaces at the beginning and end of string. For e.g. I\'ve got a string like:

\\r\\n\\t- Someone will come here?\\n- I d

8条回答
  •  盖世英雄少女心
    2021-01-14 02:19

    //here i have used regular expression and replaced white spaces at the start and end
          let stringPassing : NSString? = "hdfjkhsdj hfjksdhf sdf "
          do {
            print("old->\(stringPassing)")
            let pattern : String = "(^\\s+)|(\\s+)$"
            let regex = try NSRegularExpression(pattern: pattern , options: [])
            let newMatched = regex.matchesInString(stringPassing! as String, options: [], range: NSMakeRange(0,stringPassing!.length))
            if(newMatched.count > 0){
    
              let modifiedString = regex.stringByReplacingMatchesInString(stringPassing! as String, options: [] , range: NSMakeRange(0,stringPassing!.length), withTemplate: "")
                  print("new->\(modifiedString)")
            }
    
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    

提交回复
热议问题