Last active
August 11, 2017 07:15
-
-
Save nikeshkrjha/b380b27d37324a0db288afe9c5507b01 to your computer and use it in GitHub Desktop.
Working with characters in Strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var someString = "Hello there" | |
//Create a string using array of characters | |
let charArray: [Character] = ["N","I","K","E", "S", "H"] | |
let srtingFromArray = String(charArray) // "NIKESH" | |
//Get array of characters from a string | |
var charatctesFromString = Array(someString) // ["H", "e", "l", "l", "o", " ", "t", "h", "e", "r", "e"] | |
print(charatctesFromString) | |
//characters count in string | |
var numberOfCharacters = someString.count | |
//print all the characters in a string | |
for char in someString{ | |
print(char) | |
} | |
//H | |
//e | |
//l | |
//l | |
//o | |
// | |
//t | |
//h | |
//e | |
//r | |
//e | |
//Access characters at different index | |
var firstCharacter = someString.first | |
var lastCharacter = someString.last | |
//get character at nth index | |
func getCharAt(index: Int, string: String) -> Character { | |
let index = string.index (string.startIndex, offsetBy: index) | |
return string[index] | |
} | |
var char1 = getCharAt(index: 6, string: "Apple Inc") // I | |
//get substring bty specifying and start and end indices | |
func substring(string: String, fromIndex: Int, toIndex: Int) -> String? { | |
if fromIndex < toIndex && toIndex < string.count /*use string.characters.count for swift3*/{ | |
let startIndex = string.index(string.startIndex, offsetBy: fromIndex) | |
let endIndex = string.index(string.startIndex, offsetBy: toIndex) | |
return String(string[startIndex..<endIndex]) | |
}else{ | |
return nil | |
} | |
} | |
substring(string: "Hello World", fromIndex: 0, toIndex: 3)! // Hel | |
substring(string: "Hello World", fromIndex: 0, toIndex: 20) // nil | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment