Swift - Strings
String
To declare a string, use let or var keyword.
var greeting = "Hello" // Mutable string
let name = “Alice” // Immutable string
let keyword creates an immutable string. var creates a mutable string.
To modify a string later in code, use var keyword. let will throw error.
Swift provides a list of common methods extending String class. These methods will perform various operations with strings. Let’s have a look at few of those commonly used methods.
To check the variable is String type
let stringObject = "String here"
if stringObject is String {
print ("Yes") // Yes
}
To check if two strings are equal
let greet1 = "Hello guest"
let greet2 = "Hello world"
if greet1 == greet2 {
print ("same greeting")
}
else {
print ("different greetings")
}
To capitalise all the words
var greeting = "hello guest"
print (greeting.capitalizedString) // HELLO GUEST
To append a string
greeting += "Guest"
print (greeting) // Hello Guest
To check whether a string has particular character, use regular expression
let greeting = "Cherry blue"
if greeting.rangeOfString("r+", options: .RegularExpressionSearch) != nil {
print ("Found it") // Found it
}
To check a string contains another string
let greeting = "berry blue"
if greeting.rangeOfString("blue") != nil {
print ("yes") // yes
}
To check a string has a particular prefix
let greeting = "Super man"
if greeting.hasPrefix ("Sup") {
print ("Yes, Prefix found")
}
else {
print ("Not found")
}
To check a string has a particular suffix
let greeting = "Super man"
if greeting.hasSuffix ("man") {
print ("Yes, Suffix found")
}
else {
print ("Not found")
}
To check a string is empty
let sauce = "tomato"
if sauce.isEmpty {
print ("Empty string")
}
To generate a unique string
let uniqueString = NSUUID().UUIDString
print (uniqueString) // generated unique string
To get a substring from a range of string
let lengthy = "this is a lengthy string"
let small = lengthy[lengthy.startIndex.advanceBy(7)..
print (small) // a lengthy string
To get the string characters count
let lengthy = "this is a lengthy string"
print (lengthy.characters.count) // 24
To replace an occurrence of a string
let greeting = "Good Morning"
let greet = greeting.stringByReplacingOccurrencesOfString("Morning", with: "Evening")
print (greet) // Good Evening
To reverse a string characters
let straight = "Hello"
let reverse = String(straight.characters.reverse())
print (reverse) // olleh
To split a string into many sub string and store them in an array
let greet = "Hello world"
var arrayGreet = greet.componentsSeparatedByString(" ")
print (arrayGreet)
To trim white space in a string
let greet = "Hello world "
var trimmedGreet = greet.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
print (trimmedGreet)
Comments
Post a Comment