Reputation: 203
I have some string like "Md. Monir-Uz-Zaman Monir", "Md. Monir-Uz-Zaman Monir01", "Md. Monir-Uz-Zaman Monir876" .... Now I want to take a substring from 20th position character to last. Actually I want output like "Monir","Monir01", "Monir876"... The full string is not fixed but 1st 19 character is fixed.
I have done it in swift 2. But what would be answer for swift 3.
let nameString = str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(19), end: str.endIndex.advancedBy(0)))
Upvotes: 1
Views: 111
Reputation: 2459
// swift 3
let input = "Md. Monir-Uz-Zaman Monir"
let start = input.index(input.startIndex, offsetBy: 19)
let required = input[start..<input.endIndex] // "Monir
Upvotes: 1
Reputation: 72440
Use map(_:)
with array and then simply use substring(from:)
with shorthand argument.
let strArray = ["Md. Monir-Uz-Zaman Monir", "Md. Monir-Uz-Zaman Monir01", "Md. Monir-Uz-Zaman Monir876"]
let nameArray = strArray.map { $0.substring(from: $0.index($0.startIndex, offsetBy: 19)) }
print(nameArray) //["Monir", "Monir01", "Monir876"]
Upvotes: 2
Reputation: 3089
Convert string to array and get last object. Try below code
let string : String = "Md. Monir-Uz-Zaman Monir"
let fullNameArr = string.characters.split{$0 == " "}.map(String.init)
print(fullNameArr[fullNameArr.count-1])
Upvotes: 1