Reputation: 1604
I wanted to know how would you delete the rest of a string after a certain character. I know how to replace the occurrences of a string but don't know how would you delete the rest of the string after a certain character. Example
let names = ["Tommy-normal", "Bob-fat", "Jack-skinny", "Rob-obese"]
for x in names {
print(x.replacingOccurrences(of: "-", with: " "))
}
Instead I would like to just delete the rest of the string that comes after - so it will just print out Tommy, Bob, Jack and Rob.
Would appreciate any Help.
Upvotes: 0
Views: 88
Reputation: 131408
If you want to do it using Sulthan's suggestion (vadian's 2nd approach) but want to make it slightly more general-purpose you could create a function that extracts the first part of a string up to a delimiter, and then use that:
func firstPart(of aString: String, separator: String) -> String {
if let range = aString.range(of: separator) {
return aString.substring(to: range.lowerBound)
}
return aString
}
let names = ["Tommy", "Bob-fat", "Jack-skinny", "Rob-obese"]
let firstParts: [String] = names.map {
firstPart(of: $0, separator: "-")
}
print("firstParts = \(firstParts)")
That gives the result:
firstParts = ["Tommy", "Bob", "Jack", "Rob"]
You could also write code that maps your original array into tuples with a name part and a "morphology" part:
let tuples = names
.map{$0.components(separatedBy: "-")}
.map{(name:$0[0], morphology: $0.count > 1 ? $0[1] : "unkown morphology")}
tuples.forEach{ print($0.name + " is " + $0.morphology) }
With my version of your data, where I deleted the "-normal" part of "Tommy-normal", to make sure the code handled missing suffixes, I get:
Tommy is unkown morphology
Bob is fat
Jack is skinny
Rob is obese
Upvotes: 0
Reputation: 35
You could try this:
let names = ["Tommy-normal", "Bob-fat", "David", "Jack-skinny", "Rob-obese"]; for (let name of names) { let index = name.indexOf("-"); if (index >= 0) name = name.substring(0, index); console.log(name); }
Be careful when the word starts with "-".
I hope this helps you!
Upvotes: 0
Reputation: 1484
You could split into an array and take the first element as below:
var names = ["Tommy-normal", "Bob-fat", "Jack-skinny", "Rob-obese"]
for name in names {
let arr = name.components(separatedBy: "-")
print(arr[0])
}
Prints:
Tommy
Bob
Jack
Rob
Upvotes: 0
Reputation: 285069
A possible solution is map
with a closure
var names = ["Tommy-normal", "Bob-fat", "Jack-skinny", "Rob-obese"]
names = names.map { string -> String in
if let range = string.range(of: "-") {
return string.substring(to: range.lowerBound)
}
return string
}
Or
names = names.map { string -> String in
if let index = string.characters.index(of: "-") {
return string.substring(to: index)
}
return string
}
Upvotes: 2