4

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 don't know for sure...\r\n\r\n

And I need to remove whitespaces only at the end and beginning (string should be look like: - Someone will come here?\n- I don't know for sure... Also there could be a lot of variants of string end: "\r\n\r\n", "\r\n", "\n\r\n" and so on...

Thanks.

Denis Rumiantsev
  • 187
  • 1
  • 2
  • 8
  • Possible duplicate of [Does swift has trim method on String?](http://stackoverflow.com/questions/26797739/does-swift-has-trim-method-on-string) – Eric Aya Nov 02 '15 at 12:34

10 Answers10

21

Your string contains not only whitespace but also new line characters.

Use stringByTrimmingCharactersInSet with whitespaceAndNewlineCharacterSet.

let string = "\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n"
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

In Swift 3 it's more cleaned up:

let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
vadian
  • 274,689
  • 30
  • 353
  • 361
5

String trimming first and last whitespaces and newlines in Swift 4+

"  2 space  ".trimmingCharacters(in: .whitespacesAndNewlines)

result: "2 space"

Rafat touqir Rafsun
  • 2,777
  • 28
  • 24
3
//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)
    }
good4pc
  • 711
  • 4
  • 17
2

You can use this extension and just call "yourString".trim()

extension String
{
    func trim() -> String
    {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}
Omkar Guhilot
  • 1,712
  • 11
  • 17
1

If you want to remove Whitespace from the start of the string Try this Code.

func removeSpace()->String{
    let txt = myString
    var count:Int! = 0
    for i in txt{
        if i  == " "{
            count += 1
        }else{
            if count != 0{
                return String(txt.dropFirst(count))
            }else{
                return txt
            }
        }
    }
    return ""
}

`

1

Remove all whiteSpaces from the start of string

func removeWhiteSpaces(str:String) -> String{
    var newStr = str
    for i in 0..<str.count{
        let index = str.index(str.startIndex, offsetBy: i)
        print(str[index])
        if str[index] != " "{
            return newStr
        }
        else{
            newStr.remove(at: newStr.startIndex)
        }
    }
    return newStr
}
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
-1

In this code to restrict Textfield beginning white space

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (textField.text?.count)! == 0 && string == " " {
            return false
        }
        else{
            return true
        }
    }
selva raj
  • 154
  • 5
-1

In Swift 4 Use it on any String type variable.

extension String {
    func trimWhiteSpaces() -> String {
        let whiteSpaceSet = NSCharacterSet.whitespaces
        return self.trimmingCharacters(in: whiteSpaceSet)
    }
}

And Call it like this

yourString.trimWhiteSpaces()
Hanny
  • 1,322
  • 15
  • 20
-2

You could first remove from the beginning and then from the end like so:

while true {
if sentence.characters.first == "\r\n" || sentence.characters.first == "\n" {
    sentence.removeAtIndex(sentence.startIndex)
} else {
    break
}
}

while true {
if sentence.characters.last == "\r\n" || sentence.characters.last == "\n" {
    sentence.removeAtIndex(sentence.endIndex.predecessor())
} else {
    break
}
}
Alexander Li
  • 781
  • 4
  • 12
  • 1
    I bet this is not a good idea to use while-true loop for such problem. By the way, string ending/beginning could be different. There are a lot of cases, and write all them down - also not good idea, as I think. – Denis Rumiantsev Nov 02 '15 at 09:00
  • It breaks out of the loop once all of the spaces are removed (any combination of \n and \r\n. It will always trim the white spaces (and new lines) at the beginning and end ONLY. You should at least try it before down voting it. – Alexander Li Nov 02 '15 at 09:08
-2

let string = " exam ple "

let trimmed = string.replacingOccurrences(of: "(^\s+)|(\s+)$", with: "", options: .regularExpression)

print(">" + trimmed3 + "<")

// prints >exam ple<

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53