C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: Lowercased() changes the letters back to their original case. Each method call creates a string copy.
Swift program that uses uppercased, lowercased
let phrase = "cat and dog"
// Get uppercase form of string.
let upper = phrase.uppercased()
print(upper)
// Get lowercase form.
let lower = upper.lowercased()
print(lower)
Output
CAT AND DOG
cat and dog
Test: We find the continent names are correctly capitalized. And chars after commas, pluses and dashes (hyphens) are also uppercased.
Swift program that uses capitalized
import Foundation
// Use capitalized to uppercase the first letters.
let phrase = "antarctica, asia, africa"
let upperFirst = phrase.capitalized
print(phrase)
print(upperFirst)
// Characters after punctuation are uppercased.
let test = "ab,cd+ef-gh"
let upperFirstTest = test.capitalized
print(test)
print(upperFirstTest)
Output
antarctica, asia, africa
Antarctica, Asia, Africa
ab,cd+ef-gh
Ab,Cd+Ef-Gh
OrderedSame: When we get a ComparisonResult.orderedSame, we know the two strings are equal except for casing.
Swift program that uses caseInsensitiveCompare
import Foundation
// These strings have different cases.
let upper = "CAT"
let lower = "cat"
// Use caseInsensitiveCompare to compare the strings.
let result = upper.caseInsensitiveCompare(lower)
// If orderedSame the strings are equal except for case.
if result == ComparisonResult.orderedSame {
print("Strings have same order")
}
Output
Strings have same order
Memoization: This is an example of memoization—the program caches a result, and avoids recomputing it.
Note: If an operation is done many times, memoization can improve significantly a program's performance.
Swift program that uses dictionary, lowercased strings
var cache = [String: String]()
func lowercasedCache(value: String) -> String {
// Use the dictionary to avoid calling lowercased on a string 2 times.
let result = cache[value]
if result != nil {
print("Cache used")
return result!
}
// Store initial value in cache.
let lower = value.lowercased()
cache[value] = lower
return lower
}
// Use our caching lowercase func.
var test = "VALUE"
print("Lower: " + lowercasedCache(value: test))
print("Lower: " + lowercasedCache(value: test))
Output
Lower: value
Cache used
Lower: value