1

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)))
spectre_d2
  • 193
  • 15
  • 1
    Possible duplicate of [How does String substring work in Swift 3](http://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift-3) – karthikeyan Apr 17 '17 at 06:18
  • Possible duplicate of [How do you use String.substringWithRange? (or, how do Ranges work in Swift?)](http://stackoverflow.com/questions/24044851/how-do-you-use-string-substringwithrange-or-how-do-ranges-work-in-swift) – nayem Apr 17 '17 at 06:30

3 Answers3

2

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"]
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1

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])
kb920
  • 3,039
  • 2
  • 33
  • 44
1
// swift 3
let input = "Md. Monir-Uz-Zaman Monir"
let start = input.index(input.startIndex, offsetBy: 19)
let required = input[start..<input.endIndex] // "Monir
Benzi
  • 2,439
  • 18
  • 25