Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all line breaks at the beginning of a string in Swift

Tags:

string

swift

I have a string like this:

"  BLA Blub" 

Now I would like to remove all leading line breaks. (But only the ones until the first "real word" appears. How is this possible?

Thanks

like image 441
Christian Avatar asked Mar 10 '15 07:03

Christian


People also ask

How do I remove all spaces from a string in Swift?

To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered.

How do you remove line breaks from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

How do you remove leading and trailing spaces in Swift?

To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.

How do I remove last 4 characters from a string Swift?

To remove last character of a String in Swift, call removeLast() method on this string. String. removeLast() method removes the last character from the String.


1 Answers

If it is acceptable that newline (and other whitespace) characters are removed from both ends of the string then you can use

let string = "\n\nBLA\nblub" let trimmed = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) // In Swift 1.2 (Xcode 6.3): let trimmed = (string as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) 

To remove leading newline/whitespace characters only you can (for example) use a regular expression search and replace:

let trimmed = string.stringByReplacingOccurrencesOfString("^\\s*",     withString: "", options: .RegularExpressionSearch) 

"^\\s*" matches all whitespace at the beginning of the string. Use "^\\n*" to match newline characters only.

Update for Swift 3 (Xcode 8):

let trimmed = string.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression) 
like image 190
Martin R Avatar answered Sep 19 '22 14:09

Martin R