Swift에 startsWith () 메소드 또는 이와 유사한 것이 있습니까?
기본적으로 특정 문자열이 다른 문자열로 시작하는지 확인하려고합니다. 또한 대소 문자를 구분하지 않기를 바랍니다.
당신이 알 수 있듯이, 나는 간단한 검색 기능을 시도하고 있지만 이것에 비참하게 실패하고있는 것 같습니다.
이것이 내가 원하는 것입니다 :
“sa”를 입력하면 “San Antonio”, “Santa Fe”등의 결과가 표시됩니다. “SA”또는 “Sa”또는 “sA”를 입력해도 “San Antonio”또는 “Santa Fe”도 반환해야합니다.
나는 사용하고 있었다
self.rangeOfString(find, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil
iOS9 이전에는 잘 작동했습니다. 그러나 iOS9로 업그레이드 한 후에는 작동이 중지되었으며 이제 검색은 대소 문자를 구분합니다.
var city = "San Antonio"
var searchString = "san "
if(city.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil){
print("San Antonio starts with san ");
}
var myString = "Just a string with san within it"
if(myString.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil){
print("I don't want this string to print bc myString does not start with san ");
}
답변
hasPrefix
대신에 사용하십시오 startsWith
.
예:
"hello dolly".hasPrefix("hello") // This will return true
"hello dolly".hasPrefix("abc") // This will return false
답변
다음은 startsWith의 Swift 확장 구현입니다.
extension String {
func startsWith(string: String) -> Bool {
guard let range = rangeOfString(string, options:[.AnchoredSearch, .CaseInsensitiveSearch]) else {
return false
}
return range.startIndex == startIndex
}
}
사용법 예 :
var str = "Hello, playground"
let matches = str.startsWith("hello") //true
let no_matches = str.startsWith("playground") //false
답변
대소 문자를 구분하지 않는 접두사 일치를 구체적으로 대답하려면 다음을 수행하십시오 .
순수한 스위프트 (대부분 권장)
extension String {
func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
return lowercased().hasPrefix(prefix.lowercased())
}
}
또는:
extension String {
func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
return lowercased().starts(with: prefix.lowercased())
}
}
참고 : 빈 접두사에 대해서는 ""
두 구현이 모두 반환됩니다.true
재단 사용 range(of:options:)
extension String {
func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
return range(of: prefix, options: [.anchored, .caseInsensitive]) != nil
}
}
주의 : 빈 접두사 ""
가 돌아갑니다false
그리고 정규식으로 추한 것 (나는 그것을 보았습니다 …)
extension String {
func caseInsensitiveHasPrefix(_ prefix: String) -> Bool {
guard let expression = try? NSRegularExpression(pattern: "\(prefix)", options: [.caseInsensitive, .ignoreMetacharacters]) else {
return false
}
return expression.firstMatch(in: self, options: .anchored, range: NSRange(location: 0, length: characters.count)) != nil
}
}
주의 : 빈 접두사 ""
가 돌아갑니다false
답변
신속한에서 4 func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix) -> Bool where PossiblePrefix : Sequence, String.Element == PossiblePrefix.Element
소개합니다.
사용 예 :
let a = 1...3
let b = 1...10
print(b.starts(with: a))
// Prints "true"
답변
편집 : Swift 3 용으로 업데이트되었습니다.
Swift String 클래스에는 대소 문자를 구분하는 메소드 hasPrefix()
가 있지만 대소 문자를 구분하지 않고 검색하려면 NSString 메소드를 사용할 수 있습니다 range(of:options:)
.
참고 : 기본적으로 NSString 메서드는 사용할 수 없지만 사용 가능한 경우 에는 사용할 수 없습니다import Foundation
.
그래서:
import Foundation
var city = "San Antonio"
var searchString = "san "
let range = city.range(of: searchString, options:.caseInsensitive)
if let range = range {
print("San Antonio starts with san at \(range.startIndex)");
}
옵션은 .caseInsensitive
또는 로 지정할 수 있습니다 [.caseInsensitive]
. 다음과 같은 추가 옵션을 사용하려면 두 번째 옵션을 사용하십시오.
let range = city.range(of: searchString, options:[.caseInsensitive, .backwards])
이 방법은 또한 검색과 같은 다른 옵션을 검색에 사용할 수 있다는 장점이 있습니다 .diacriticInsensitive
. 단순히 . lowercased()
문자열 을 사용하여 동일한 결과를 얻을 수는 없습니다 .
답변
스위프트 3 버전 :
func startsWith(string: String) -> Bool {
guard let range = range(of: string, options:[.caseInsensitive]) else {
return false
}
return range.lowerBound == startIndex
}
답변
확장 기능이있는 Swift 4에서
내 확장 예제에는 3 가지 기능이 포함되어 있습니다. check subString 으로 문자열 시작 , subString으로 문자열 끝 수행 및 문자열 에 subString 포함 이 있습니다.
“A”또는 “a”문자를 무시하려면 isCaseSensitive-parameter를 false로 설정하고, 그렇지 않으면 true로 설정하십시오.
작동 방식에 대한 자세한 내용은 코드의 주석을 참조하십시오.
암호:
import Foundation
extension String {
// Returns true if the String starts with a substring matching to the prefix-parameter.
// If isCaseSensitive-parameter is true, the function returns false,
// if you search "sA" from "San Antonio", but if the isCaseSensitive-parameter is false,
// the function returns true, if you search "sA" from "San Antonio"
func hasPrefixCheck(prefix: String, isCaseSensitive: Bool) -> Bool {
if isCaseSensitive == true {
return self.hasPrefix(prefix)
} else {
var thePrefix: String = prefix, theString: String = self
while thePrefix.count != 0 {
if theString.count == 0 { return false }
if theString.lowercased().first != thePrefix.lowercased().first { return false }
theString = String(theString.dropFirst())
thePrefix = String(thePrefix.dropFirst())
}; return true
}
}
// Returns true if the String ends with a substring matching to the prefix-parameter.
// If isCaseSensitive-parameter is true, the function returns false,
// if you search "Nio" from "San Antonio", but if the isCaseSensitive-parameter is false,
// the function returns true, if you search "Nio" from "San Antonio"
func hasSuffixCheck(suffix: String, isCaseSensitive: Bool) -> Bool {
if isCaseSensitive == true {
return self.hasSuffix(suffix)
} else {
var theSuffix: String = suffix, theString: String = self
while theSuffix.count != 0 {
if theString.count == 0 { return false }
if theString.lowercased().last != theSuffix.lowercased().last { return false }
theString = String(theString.dropLast())
theSuffix = String(theSuffix.dropLast())
}; return true
}
}
// Returns true if the String contains a substring matching to the prefix-parameter.
// If isCaseSensitive-parameter is true, the function returns false,
// if you search "aN" from "San Antonio", but if the isCaseSensitive-parameter is false,
// the function returns true, if you search "aN" from "San Antonio"
func containsSubString(theSubString: String, isCaseSensitive: Bool) -> Bool {
if isCaseSensitive == true {
return self.range(of: theSubString) != nil
} else {
return self.range(of: theSubString, options: .caseInsensitive) != nil
}
}
}
사용 방법 예 :
확인을 위해 문자열은 “TEST”로 시작합니다.
"testString123".hasPrefixCheck(prefix: "TEST", isCaseSensitive: true) // Returns false
"testString123".hasPrefixCheck(prefix: "TEST", isCaseSensitive: false) // Returns true
확인을 위해 문자열은 “test”로 시작합니다.
"testString123".hasPrefixCheck(prefix: "test", isCaseSensitive: true) // Returns true
"testString123".hasPrefixCheck(prefix: "test", isCaseSensitive: false) // Returns true
확인을 위해 문자열은 “G123″으로 끝납니다.
"testString123".hasSuffixCheck(suffix: "G123", isCaseSensitive: true) // Returns false
"testString123".hasSuffixCheck(suffix: "G123", isCaseSensitive: false) // Returns true
확인을 위해 문자열은 “g123″으로 끝납니다.
"testString123".hasSuffixCheck(suffix: "g123", isCaseSensitive: true) // Returns true
"testString123".hasSuffixCheck(suffix: "g123", isCaseSensitive: false) // Returns true
확인을 위해 문자열에는 “RING12″가 포함됩니다.
"testString123".containsSubString(theSubString: "RING12", isCaseSensitive: true) // Returns false
"testString123".containsSubString(theSubString: "RING12", isCaseSensitive: false) // Returns true
확인을 위해 문자열에는 “ring12″가 포함됩니다.
"testString123".containsSubString(theSubString: "ring12", isCaseSensitive: true) // Returns true
"testString123".containsSubString(theSubString: "ring12", isCaseSensitive: false) // Returns true