How to compare two strings ignoring case in Swift language?
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")
}
Non-case-sensitive switch statement in swift?
You could uppercase text
(or lowercase [lowercased()
] as mentioned in the comments), so case would not matter:
switch text.uppercased() {
case "HI", "HELLO", "GOOD DAY":
return "Hello, sir."
default:
return "Sorry, I didn't understand!"
}
Compare two strings?]
if "test".contains("es") {
//...
}
Case insensitive comparison NSString
if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
// strings are equal except for possibly case
}
The documentation is located at Search and Comparison Methods
Check if a string exists in an array case insensitively
you can use
word.lowercaseString
to convert the string to all lowercase characters
How to compare two Strings to check if they have same Characters Swift 4?
If “multiplicity” counts (i.e. "aab" has the same characters as "aba",
but not the same characters as "abb"), then
s1.sorted() == s2.sorted()
does the trick. If you don't care about the multiplicity, then just
Set(s1) == Set(s2)
Example:
let firstArray = ["sumit", "ambuj", "abhi", "aba"]
let secondArray = ["mitsu", "jumba", "hibb", "abb"]
for (s1, s2) in zip(firstArray, secondArray) {
print(s1.sorted() == s2.sorted())
}
// true, true, false, false
for (s1, s2) in zip(firstArray, secondArray) {
print(Set(s1) == Set(s2))
}
// true, true, false, true
For longer strings it might be more efficient to maintain a
dictionary with the number of occurrences of each character in
a string (similar to a NSCountedSet
):
func characterCounts(_ s: String) -> [Character: Int] {
return s.reduce(into: [:], { $0[$1, default: 0] += 1 })
}
and then compare the dictionaries:
characterCounts(s1) == characterCounts(s2)
case insensitive matching search in string array swift 3
You can try with localizedCaseInsensitiveContains
let filteredArray = self.arrCountry.filter { $0.localizedCaseInsensitiveContains("india") }
Comparing String ignoring spaces at the beginning or ending
NSString *string1 = @" Hello";
//remove(trim) whitespaces
string1 = [string1 stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *string2 = @"Hello ";
//remove(trim) whitespaces
string2 = [string1 stringByReplacingOccurrencesOfString:@" " withString:@""]
// compare strings without whitespaces
if ([string1 isEuqalToString:string2]) {
}
So if you want to use it directly -
if ([[yourString1 stringByReplacingOccurrencesOfString:@" " withString:@""] isEuqalToString:[yourString2 stringByReplacingOccurrencesOfString:@" " withString:@""]]) {
// Strings are compared without whitespaces.
}
Above will remove all whitespaces of your string, if you want to remove only leading and trailing whitespaces then there are a couple of post already available, you can create a category of string as mentioned in following stack overflow post - How to remove whitespace from right end of NSString?
@implementation NSString (TrimmingAdditions)
- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (location; location < length; location++) {
if (![characterSet characterIsMember:charBuffer[location]]) {
break;
}
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];
for (length; length > 0; length--) {
if (![characterSet characterIsMember:charBuffer[length - 1]]) {
break;
}
}
return [self substringWithRange:NSMakeRange(location, length - location)];
}
@end
Now once you have the methods available, you can call these on your strings to trim leading and trailing spaces like -
// trim leading chars
yourString1 = [yourString1 stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// trim trainling chars
yourString1 = [yourString1 stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// trim leading chars
yourString2 = [yourString2 stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// trim trainling chars
yourString2 = [yourString2 stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// compare strings
if([yourString1 isEqualToString: yourString2]) {
}
Related Topics
App Transport Security Xcode 7 Beta 6
How to Set the Position of the Cursor in Uitextview
Icon Already Includes Gloss Effects
New React Native Project with Old Version of React Native
Xcode Won't Let to Build for Device After Denying Codesign to Access Keychain
Why Tesseract Ocr Library (Ios) Cannot Recognize Text at All
Xcode Instruments Allocations: Look at Live Bytes or Overall Bytes
Load Image from Bundle with iOS
Uiscrollview Adjusts Contentoffset When Contentsize Changes
How to Update Uibutton Title/Text Programmatically
Uitextview Disabling Text Selection
Does iOS Provide Built in Text to Speech Support or Any Class Like Nsspeechrecognizer
What Privacy-Violating or Device-Changing Things How to Do on an Iphone