Get nth character of a String & get a Substring from a String
To get n character of a String in Swift you simply use Index, same to get a substring.
The code below does the following:
- Get the nth character from a String (1)
- Get the nth character from the End of a String (2)
- Get a Substring from a string from X position to Y position (3)
- Get a Substring starting a nth character to the end of the String (4)
- Get a Substring starting at the start of a string to the nth character (5)
let str = "Seemu Apps" // 1 // Get a character at X position (index) let index = str.characters.index(str.startIndex, offsetBy: 4) let startChar = str[index] // returns Character 'u' print(startChar) // 2 // Get a character at X position (index) starting from the end of the string let endIndex = str.characters.index(str.endIndex, offsetBy: -2) // Goes to the end of the string and back to characters let endChar = str[endIndex] // returns Character "p" print(endChar) // 3 // Get the substring, starting from index and ending at endIndex let subString = str[(index ..< endIndex)] print(subString) // returns "u Ap" // 4 & 5 // Get the substring starting from Index until the End of the String let indexToEnd = str.substring(from: index) // Get the substring starting frmo the Start of the String to the Index let startToIndex = str.substring(to: index) print(indexToEnd) // returns String "u Apps" print(startToIndex) // returns String "Seem"
It will output the results to the console as you can see in the comments. You can download the source code below if you wish to see it in action and play around with it!
a