How to Trim a String in Swift based on a character
You can use String method rangeOfString:
let link = "https://s3.amazonaws.com/brewerydbapi/beer/RXI2cT/upload_FfAPfl-icon.png"
if let range = link.rangeOfString("_") {
let fileName = link.substringFromIndex(range.endIndex)
print(fileName) // "FfAPfl-icon.png\n"
}
Xcode 8 beta 3 • Swift 3
if let range = link.range(of: "_") {
let fileName = link.substring(from: range.upperBound)
print(fileName) // "FfAPfl-icon.png\n"
}
How to trim first 3 character from a string in swift
You can split your string where separator is a slash, drop the first component and then join it again:
let str = "66/001/0004"
let trimmed = str.split { $0 == "/" }
.dropFirst()
.joined(separator: "/") // "001/0004"
Another option is to find the first slash index and get the substring after it:
if let index = str.firstIndex(of: "/") {
let trimmed = str[str.index(after: index)...] // "001/0004"
// or simply dropping the first character
// let trimmed = str[index...].dropFirst()
}
Trimming a String inside a loop in Swift 5
You can extend String
to give you this functionality (or extract it).
extension String {
func truncate(to limit: Int, ellipsis: Bool = true) -> String {
if count > limit {
let truncated = String(prefix(limit)).trimmingCharacters(in: .whitespacesAndNewlines)
return ellipsis ? truncated + "\u{2026}" : truncated
} else {
return self
}
}
}
let default = "Coming up with this sentence was the hardest part of this.".truncate(to: 50)
print(default) // Coming up with this sentence was the hardest part…
let modified = "Coming up with this sentence was the hardest part of this.".truncate(to: 50, ellipsis: false)
print(modified) // Coming up with this sentence was the hardest part
And in your use case:
router.get("/admin", handler: { (request, response, next) in
let documents = try collection.find()
var pages: [[String: String]] = []
for d in documents {
let truncatedBody = d.body.truncate(to: 50)
pages.append(["title": d.title, "slug": d.slug, "body": truncatedBody, "date": d.date])
}
...
})
Trimming Substrings from String Swift/SwiftUI
A possible way is Regular Expression
let string = "Chest Stretch (left)"
let trimmedString = string.replacingOccurrences(of: "\\s\\([^)]+\\)", with: "", options: .regularExpression)
The found pattern will be replaced with an empty string.
The pattern is:
- One whitespace character
\\s
- An opening parenthesis
\\(
- One or more characters which are not a closing parentheses
[^)]+
- and a closing parenthesis
\\)
Or simpler if the delimiter character is always the opening parenthesis
let trimmedString = String(string.prefix(while: {$0 != "("}).dropLast())
Or
let trimmedString = string.components(separatedBy: " (").first!
Get the string up to a specific character
Expanding on @appzYourLife answer, the following will also trim off the whitespace characters after removing everything after the @ symbol.
import Foundation
var str = "hello, how are you @tom"
if str.contains("@") {
let endIndex = str.range(of: "@")!.lowerBound
str = str.substring(to: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
}
print(str) // Output - "hello, how are you"
UPDATE:
In response to finding the last occurance of the @
symbol in the string and removing it, here is how I would approach it:
var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = String(newStr.characters.reversed())
//str = "hello, how are you @tom"
}
Or looking at @appzYourLife answer use range(of:options:range:locale:)
instead of literally reversing the characters
var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Find the last occurrence of @
let endIndex = str.range(of: "@", options: .backwards, range: nil, locale: nil)!.lowerBound
//Get the string up to and after the @ symbol
let newStr = str.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = newStr
//str = "hello, how are you @tom"
}
As an added bonus, here is how I would approach removing every @
starting with the last and working forward:
var str = "hello, how are you @tom and @tim?"
if str.contains("@") {
while str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = String(newStr.characters.reversed())
}
//after while loop, str = "hello, how are you"
}
Trim String before specific character?
Get the first index of the dot and get the substring after that index
let str = "asderwt.qwertyu.zxcvbbnnhg"
if let index = str.firstIndex(where: { $0 == "." }) {
print(str[index...])//.qwertyu.zxcvbbnnhg
}
Does swift have a trim method on String?
Here's how you remove all the whitespace from the beginning and end of a String
.
(Example tested with Swift 2.0.)
let myString = " \t\t Let's trim all the whitespace \n \t \n "
let trimmedString = myString.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"
(Example tested with Swift 3+.)
let myString = " \t\t Let's trim all the whitespace \n \t \n "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"
Remove the first six characters from a String (Swift)
length
is the number of characters you want to remove (6 in your case)
extension String {
func toLengthOf(length:Int) -> String {
if length <= 0 {
return self
} else if let to = self.index(self.startIndex, offsetBy: length, limitedBy: self.endIndex) {
return self.substring(from: to)
} else {
return ""
}
}
}
Swift - Remove character from string
Swift uses backslash to escape double quotes. Here is the list of escaped special characters in Swift:
\0
(null character)\\
(backslash)\t
(horizontal tab)\n
(line feed)\r
(carriage return)\"
(double quote)\'
(single quote)
This should work:
text2 = text2.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)
Related Topics
@Objc Redundancy When Having @Objcmembers Private Dynamic Var
Nswindow with Round Corners in Swift
Getting an Issue with Upgrade to Xcode 10.2
Nsposixerrordomain When Binding to Socket on MACos 10.12
Module Compiled with Swift 4.0 Cannot Be Imported in Swift 3.0.2
Increment Integer in Nsuserdefaults
How to Use a Completion Handler to Put an Image in a Swiftui View
Using a Metal Shader in Scenekit
Uiswipegesturerecognizer Doesn't Recognize Swipe Gesture Initiated Outside the View
Swift How to Assign a String to a Uitextfield
Can Not Conform to Protocol by Creating Extension with Where Clauses
Swift; Delegate Embedded View Controller and Parent
Implicitlyunwrappedoptional in Init VS Later
Swift Create Byte Buffer Holder for Nsstream
Prevent Error "Funk" Sound in Event Monitor Os X
Deleting a Camera Roll Asset Using Photos Framework