How can we compare two strings in swift ignoring case ? for eg :
var a = "Cash"
var b = "cash"
Is there any method that will return true if we compare var a & var b
How can we compare two strings in swift ignoring case ? for eg :
var a = "Cash"
var b = "cash"
Is there any method that will return true if we compare var a & var b
Try this:
var a = "Cash"
var b = "cash"
let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
// You can also ignore last two parameters(thanks 0x7fffffff)
//let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch)
result is type of NSComparisonResult enum:
enum NSComparisonResult : Int {
case OrderedAscending
case OrderedSame
case OrderedDescending
}
So you can use if statement:
if result == .OrderedSame {
println("equal")
} else {
println("not equal")
}
Try this :
For older swift:
var a : String = "Cash"
var b : String = "cash"
if(a.caseInsensitiveCompare(b) == NSComparisonResult.OrderedSame){
println("Et voila")
}
Swift 3+
var a : String = "Cash"
var b : String = "cash"
if(a.caseInsensitiveCompare(b) == .orderedSame){
print("Et voila")
}
a.caseInsensitiveCompare(b) == ComparisonResult.orderedSame
–
Rotor caseInsensitiveCompare(_:)
is not included in the Swift Standard Library, rather it is part of the Foundation
framework, thus, requiring import Foundation
. –
Repugnance a.lowercased() == b.lowercased()
? –
Bernadettebernadina a.localizedStandardRange(of: b) == a.startIndex..<a.endIndex
seems to work better for me and supports localization. The above code doesn’t work for all languages (case rules may differ). Also all localized*Compare()
return false if a = "Et voila"
and b = "Et voilà"
, when it should be true. –
Frig Use caseInsensitiveCompare
method:
let a = "Cash"
let b = "cash"
let c = a.caseInsensitiveCompare(b) == .orderedSame
print(c) // "true"
ComparisonResult tells you which word comes earlier than the other in lexicographic order (i.e. which one comes closer to the front of a dictionary). .orderedSame
means the strings would end up in the same spot in the dictionary
.orderedSame
mean? The docs just say The two operands are equal. But why is the word 'order' used here? Is there a sequence or something? And what does The left operand is smaller than the right operand. (.orderedAscending
) mean for strings –
Pellet .orderedSame
means the strings would end up in the same spot in the dictionary. –
Combo .orderedSame
is short for ComparisonResult.orderSame
... you don't have to name the type since the compiler knows that caseInsensitiveCompare
returns a ComparisonResult
. "The two operands are equal" -- they are equal according to a specific ordering ... clearly, "Cash" and "cash" are not identical string values. "But why is the word 'order' used here?" -- because it's the result of an ordered comparison. The other values are orderedAscending
and orderedDescending
... it's not just a question of same or different. As for "smaller": strings are like numbers in a large base. –
Quenby a.caseInsensitiveCompare(b, comparing: .orderedSame)
would have been more readable... –
Pellet if a.lowercaseString == b.lowercaseString {
//Strings match
}
Try this:
var a = "Cash"
var b = "cash"
let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)
// You can also ignore last two parameters(thanks 0x7fffffff)
//let result: NSComparisonResult = a.compare(b, options: NSStringCompareOptions.CaseInsensitiveSearch)
result is type of NSComparisonResult enum:
enum NSComparisonResult : Int {
case OrderedAscending
case OrderedSame
case OrderedDescending
}
So you can use if statement:
if result == .OrderedSame {
println("equal")
} else {
println("not equal")
}
localizedCaseInsensitiveContains : Returns whether the receiver contains a given string by performing a case-insensitive, locale-aware search
if a.localizedCaseInsensitiveContains(b) {
//returns true if a contains b (case insensitive)
}
Edited:
caseInsensitiveCompare : Returns the result of invoking compare(_:options:) with NSCaseInsensitiveSearch as the only option.
if a.caseInsensitiveCompare(b) == .orderedSame {
//returns true if a equals b (case insensitive)
}
CORRECT WAY:
let a: String = "Cash"
let b: String = "cash"
if a.caseInsensitiveCompare(b) == .orderedSame {
//Strings match
}
Please note: ComparisonResult.orderedSame can also be written as .orderedSame in shorthand.
OTHER WAYS:
a.
if a.lowercased() == b.lowercased() {
//Strings match
}
b.
if a.uppercased() == b.uppercased() {
//Strings match
}
c.
if a.capitalized() == b.capitalized() {
//Strings match
}
Could just roll your own:
func equalIgnoringCase(a:String, b:String) -> Bool {
return a.lowercaseString == b.lowercaseString
}
Phone numbers comparison example; using swift 4.2
var selectPhone = [String]()
if selectPhone.index(where: {$0.caseInsensitiveCompare(contactsList[indexPath.row].phone!) == .orderedSame}) != nil {
print("Same value")
} else {
print("Not the same")
}
You can just write your String Extension for comparison in just a few line of code
extension String {
func compare(_ with : String)->Bool{
return self.caseInsensitiveCompare(with) == .orderedSame
}
}
For Swift 5 Ignoring the case and compare two string
var a = "cash"
var b = "Cash"
if(a.caseInsensitiveCompare(b) == .orderedSame){
print("Ok")
}
Swift 4, I went the String extension route using caseInsensitiveCompare() as a template (but allowing the operand to be an optional). Here's the playground I used to put it together (new to Swift so feedback more than welcome).
import UIKit
extension String {
func caseInsensitiveEquals<T>(_ otherString: T?) -> Bool where T : StringProtocol {
guard let otherString = otherString else {
return false
}
return self.caseInsensitiveCompare(otherString) == ComparisonResult.orderedSame
}
}
"string 1".caseInsensitiveEquals("string 2") // false
"thingy".caseInsensitiveEquals("thingy") // true
let nilString1: String? = nil
"woohoo".caseInsensitiveEquals(nilString1) // false
.orderedSame
rather than ComparisonResult.orderedSame
. –
Quenby Created an extension function for it. Pass caseSensitive
as false
if you want case insensitive compare.
extension String {
func equals(to string: String, caseSensitive: Bool = true) -> Bool {
if caseSensitive {
return self.compare(string) == .orderedSame
} else {
return self.caseInsensitiveCompare(string) == .orderedSame
}
}
}
Example:
"cash".equals(to: "Cash", caseSensitive: false) //returns true
"cash".equals(to: "Cash") //returns false
Swift 3: You can define your own operator, e.g. ~=
.
infix operator ~=
func ~=(lhs: String, rhs: String) -> Bool {
return lhs.caseInsensitiveCompare(rhs) == .orderedSame
}
Which you then can try in a playground
let low = "hej"
let up = "Hej"
func test() {
if low ~= up {
print("same")
} else {
print("not same")
}
}
test() // prints 'same'
String
instances to eachother (or to other String
literals). Imagine let str = "isCAMELcase"
being switched over, with a case as follows: case "IsCamelCase": ...
. With the method above, this case
would be entered successfully, which is not expected coming from the standard libs implementation of String
pattern matching. An updated Swift 3 answer is still good though, but ... –
Footwear String
extension) as helper above rather than overriding the default String
pattern matching. –
Footwear You could also make all the letters uppercase (or lowercase) and see if they are the same.
var a = “Cash”
var b = “CASh”
if a.uppercaseString == b.uppercaseString{
//DO SOMETHING
}
This will make both variables as ”CASH”
and thus they are equal.
You could also make a String
extension
extension String{
func equalsIgnoreCase(string:String) -> Bool{
return self.uppercaseString == string.uppercaseString
}
}
if "Something ELSE".equalsIgnoreCase("something Else"){
print("TRUE")
}
Swift 3
if a.lowercased() == b.lowercased() {
}
Swift 3:
You can also use the localized case insensitive comparison between two strings function and it returns Bool
var a = "cash"
var b = "Cash"
if a.localizedCaseInsensitiveContains(b) {
print("Identical")
} else {
print("Non Identical")
}
extension String
{
func equalIgnoreCase(_ compare:String) -> Bool
{
return self.uppercased() == compare.uppercased()
}
}
sample of use
print("lala".equalIgnoreCase("LALA"))
print("l4la".equalIgnoreCase("LALA"))
print("laLa".equalIgnoreCase("LALA"))
print("LALa".equalIgnoreCase("LALA"))
© 2022 - 2024 — McMap. All rights reserved.
lowercaseString
that is mentioned in some answers will fail in some languages (Straße != STRASSE for example) – HydrosomecaseInsensitiveCompare:
&localizedCaseInsensitiveCompare:
instead – Hydrosome"Straße".localizedCaseInsensitiveCompare("STRASSE")
- Remember to importFoundation
) – Hydrosome