Remove all whitespaces from NSString

后端 未结 11 1749
北荒
北荒 2020-12-04 06:23

I\'ve been trying to get rid of the white spaces in an NSString, but none of the methods I\'ve tried worked.

I have \"this is a test\" and

11条回答
  •  有刺的猬
    2020-12-04 07:12

    This for me is the best way SWIFT

            let myString = "  ciao   \n              ciao     "
            var finalString = myString as NSString
    
            for character in myString{
            if character == " "{
    
                finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")
    
            }else{
                finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")
    
            }
    
        }
         println(finalString)
    

    and the result is : ciaociao

    But the trick is this!

     extension String {
    
        var NoWhiteSpace : String {
    
        var miaStringa = self as NSString
    
        if miaStringa.containsString(" "){
    
          miaStringa =  miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
        }
            return miaStringa as String
    
        }
    }
    
    let myString = "Ciao   Ciao       Ciao".NoWhiteSpace  //CiaoCiaoCiao
    

提交回复
热议问题