Swift 언어에서 대소 문자를 무시하고 두 문자열을 비교하는 방법은 무엇입니까?
신속한 무시 케이스에서 두 문자열을 어떻게 비교할 수 있습니까? 예 :
var a = "Cash"
var b = "cash"
var a와 var b를 비교하면 true를 반환하는 메서드가 있습니까?
이 시도 :
이전 Swift의 경우 :
var a : String = "Cash"
var b : String = "cash"
if(a.caseInsensitiveCompare(b) == NSComparisonResult.OrderedSame){
println("voila")
}
Swift 3.0 및 4.1
var a : String = "Cash"
var b : String = "cash"
if(a.caseInsensitiveCompare(b) == .orderedSame){
print("voila")
}
사용 caseInsensitiveCompare
방법 :
let a = "Cash"
let b = "cash"
let c = a.caseInsensitiveCompare(b) == .orderedSame
print(c) // "true"
ComparisonResult 는 사전 식 순서로 다른 단어보다 먼저 오는 단어를 알려줍니다 (즉, 사전의 앞쪽에 더 가까운 단어). .orderedSame
문자열이 사전의 같은 위치에 있음을 의미합니다.
if a.lowercaseString == b.lowercaseString {
//Strings match
}
이 시도:
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)
결과는 NSComparisonResult 열거 형 유형입니다.
enum NSComparisonResult : Int {
case OrderedAscending
case OrderedSame
case OrderedDescending
}
따라서 if 문을 사용할 수 있습니다.
if result == .OrderedSame {
println("equal")
} else {
println("not equal")
}
직접 굴릴 수 있습니다.
func equalIgnoringCase(a:String, b:String) -> Bool {
return a.lowercaseString == b.lowercaseString
}
스위프트 3
올바른 방법 :
let a: String = "Cash"
let b: String = "cash"
if a.caseInsensitiveCompare(b) == .orderedSame {
//Strings match
}
참고 : ComparisonResult.orderedSame은 약어로 .orderSame으로 작성할 수도 있습니다.
다른 방법들:
ㅏ.
if a.lowercased() == b.lowercased() {
//Strings match
}
비.
if a.uppercased() == b.uppercased() {
//Strings match
}
씨.
if a.capitalized() == b.capitalized() {
//Strings match
}
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")
}
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")
}
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)
}
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"))
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
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 3
if a.lowercased() == b.lowercased() {
}
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'
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")
}
'programing' 카테고리의 다른 글
Pry : 스택보기 (0) | 2020.09.15 |
---|---|
MySQL- "0"으로 우편 번호를 앞쪽으로 채우는 방법은 무엇입니까? (0) | 2020.09.15 |
카피 바라는 요소의 속성을 주장 (0) | 2020.09.15 |
Windows Forms-Enter 키를 누르면 제출 버튼이 활성화됩니까? (0) | 2020.09.15 |
ImportError : pip라는 모듈이 없습니다. (0) | 2020.09.15 |