search if NSString contains value - objective-c

I have some string value which constructed from a few characters , and i want to check if they exist in another NSString, without case sensitive, and spaces .
Example code :
NSString *me = #"toBe" ;
NSString *target=#"abcdetoBe" ;
//than check if me is in target.
Here i will get true because me exist in target .
How can i check for such condition ?
I have read How do I check if a string contains another string in Objective-C? but its case sensitive and i need to find with no case sensitive..

Use the option NSCaseInsensitiveSearch with rangeOfString:options:
NSString *me = #"toBe" ;
NSString *target = #"abcdetobe" ;
NSRange range = [target rangeOfString: me options: NSCaseInsensitiveSearch];
NSLog(#"found: %#", (range.location != NSNotFound) ? #"Yes" : #"No");
if (range.location != NSNotFound) {
// your code
}
NSLog output:
found: Yes
Note: I changed the target to demonstrate that case insensitive search works.
The options can be "or'ed" together and include:
NSCaseInsensitiveSearch
NSLiteralSearch
NSBackwardsSearch
NSAnchoredSearch
NSNumericSearch
NSDiacriticInsensitiveSearch
NSWidthInsensitiveSearch
NSForcedOrderingSearch
NSRegularExpressionSearch

-(BOOL)substring:(NSString *)substr existsInString:(NSString *)str {
if(!([str rangeOfString:substr options:NSCaseInsensitiveSearch].length==0)) {
return YES;
}
return NO;
}
usage:
NSString *me = #"toBe";
NSString *target=#"abcdetoBe";
if([self substring:me existsInString:target]) {
NSLog(#"It exists!");
}
else {
NSLog(#"It does not exist!");
}

As with the release of iOS8, Apple added a new method to NSStringcalled localizedCaseInsensitiveContainsString. This will exactly do what you want:
Swift:
let string: NSString = "ToSearchFor"
let substring: NSString = "earch"
string.localizedCaseInsensitiveContainsString(substring) // true
Objective-C:
NSString *string = #"ToSearchFor";
NSString *substring = #"earch";
[string localizedCaseInsensitiveContainsString:substring]; //true

Related

How to handle the NSString starts with "\0"

i have a NSString starts with "\0", then i read it and wants to do some action with this NSString, but i found the length is not 0 and the content is nothing.
NSString *str = #"\0afasfsafsda"; // some string read from a file
NSLog(#"%#",str); //output nothing
NSLog(#"%#", [str length]); //12
right now i want to check wheather a NSString is this type, how to do this?
if([str isEqualTo:#""] && [str length]==?)
You can check for a \0 first character like this:
NSString *str = #"\0afasfsafsda";
BOOL firstCharIsNull = (str.length > 0 && [str characterAtIndex:0] == 0);
if (firstCharIsNull) {
NSLog(#"yes");
} else {
NSLog(#"no");
}

How can I use NSNotFound in my NSString? Objective-C

How can I make this code here:
- (NSString *) cheeseNameWithoutCheeseSuffix:(NSString *)cheeseName {
/* WORK HERE */
NSString *noCheese = cheeseName;
NSRange cheeseRange = [noCheese rangeOfString:#" cheese" options:NSCaseInsensitiveSearch];
NSString *withoutCheese = [noCheese stringByReplacingCharactersInRange:cheeseRange withString:#""];
return withoutCheese;
}
Work with this code with NSNotFound?
- (void)testThatRemovingCheeseSuffixWorksWithNoCheeseAtAll {
NSString *fullCheeseString = #"Gouda";
NSString *cheeseNameOnly = [self.stringCheese cheeseNameWithoutCheeseSuffix:fullCheeseString];
XCTAssertEqualObjects(cheeseNameOnly, #"Gouda", #"Gouda should be returned.");
}
You should check that cheeseRange.location is not equal to NSNotFound. But you can just try your code to see what it does!

Cutting the length of an NSString without splitting the last word

I'm trying to cut the length of an NSString without splitting the last word with this method:
// cut a string by words
- (NSString* )stringCutByWords:(NSString *)string toLength:(int)length;
{
// search backwards in the string for the beginning of the last word
while ([string characterAtIndex:length] != ' ' && length > 0) {
length--;
}
// if the last word was the first word of the string search for the end of the word
if (length <= 0){
while ([string characterAtIndex:length] != ' ' && length > string.length-1) {
length++;
}
}
// define the range you're interested in
NSRange stringRange = {0, length};
// adjust the range to include dependent chars
stringRange = [string rangeOfComposedCharacterSequencesForRange:stringRange];
// Now you can create the short string
string = [string substringWithRange:stringRange];
return [NSString stringWithFormat:#"%#...",string];
}
now my question is:
Is there a build-in way in objective-c or cocoa-touch which i did not see or else is there a "nicer" way to do this because iam not very happy with this solution.
greetings and thanks for help
C4rmel
My proposal for a Category method
#interface NSString (Cut)
-(NSString *)stringByCuttingExceptLastWordWithLength:(NSUInteger)length;
#end
#implementation NSString (Cut)
-(NSString *)stringByCuttingExceptLastWordWithLength:(NSUInteger)length
{
__block NSMutableString *newString = [NSMutableString string];
NSArray *components = [self componentsSeparatedByString:#" "];
if ([components count] > 0) {
NSString *lastWord = [components objectAtIndex:[components count]-1];
[components enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
if (([obj length]+[newString length] + [lastWord length] + 2) < length) {
[newString appendFormat:#" %#", obj];
} else {
[newString appendString:#"…"];
[newString appendFormat:#" %#", lastWord];
*stop = YES;
}
}];
}
return newString;
}
Usage:
NSString *string = #"Hello World! I am standing over here! Can you see me?";
NSLog(#"%#", [string stringByCuttingExceptLastWordWithLength:25]);
Suggestions:
make it a category method;
use NSCharacterSet and the built-in search methods rather than rolling your own.
So:
/* somewhere public */
#interface NSString (CutByWords)
- (NSString *)stringCutByWordsToMaxLength:(int)length
#end
/* in an implementation file, somewhere */
#implementation NSString (CutByWords)
// cut a string by words
- (NSString *)stringCutByWordsToMaxLength:(int)length
{
NSCharacterSet *whitespaceCharacterSet =
[NSCharacterSet whitespaceCharacterSet];
// to consider: a range check on length here?
NSRange relevantRange = NSMakeRange(0, length);
// find beginning of last word
NSRange lastWordRange =
[self rangeOfCharacterFromSet:whitespaceCharacterSet
options:NSBackwardsSearch
range:relevantRange];
// if the last word was the first word of the string,
// consume the whole string; this looks to be the same
// effect as the original scan forward given that the
// assumption is already made in the scan backwards that
// the string doesn't end on a whitespace; if I'm wrong
// then get [whitespaceCharacterSet invertedSet] and do
// a search forwards
if(lastWordRange.location == NSNotFound)
{
lastWordRange = relevantRange;
}
// adjust the range to include dependent chars
stringRange = [self rangeOfComposedCharacterSequencesForRange:stringRange];
// Now you can create the short string
NSString *string = [self substringWithRange:stringRange];
return [NSString stringWithFormat:#"%#...",string];
}
#end
/* subsequently */
NSString *string = ...whatever...;
NSString *cutString = [string stringCutByWordsToMaxLength:100];

Find one string in another with case insensitive in Objective-C

My question is similar to How do I check if a string contains another string in Objective-C?
How can I check if a string (NSString) contains another smaller string but with ignoring case?
NSString *string = #"hello bla bla";
I was hoping for something like:
NSLog(#"%d",[string containsSubstring:#"BLA"]);
Anyway is there any way to find if a string contains another string with ignore case ? But please do not convert both strings to UpperCase or to LowerCase.
As similar to the answer provided in the link, but use options.
See - (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask in Apple doc
NSString *string = #"hello bla bla";
if ([string rangeOfString:#"BLA" options:NSCaseInsensitiveSearch].location == NSNotFound)
{
NSLog(#"string does not contain bla");
}
else
{
NSLog(#"string contains bla!");
}
From iOS 8 you can add the containsString: or localizedCaseInsensitiveContainsString method to NSString.
if ([string localizedCaseInsensitiveContainsString:#"BlA"]) {
NSLog(#"string contains Case Insensitive bla!");
} else {
NSLog(#"string does not contain bla");
}
NSString *string = #"hello BLA";
if ([string rangeOfString:#"bla" options:NSCaseInsensitiveSearch].location == NSNotFound) {
NSLog(#"string does not contain bla");
} else {
NSLog(#"string contains bla!");
}
The method
[string rangeOfString:#"bla" options:NSCaseInsensitiveSearch];
should help you.
You can use -(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask; to get a range for a substring, the mask parameter is used to specify case insensitive match.
Example :
NSRange r = [str rangeOfString:#"BLA"
options:NSCaseInsensitiveSearch];
As stated in the documentation, the method returns a range like {NSNotFound, 0} when the substring isn't found.
BOOL b = r.location == NSNotFound;
Important this method raises an exception if the string is nil.
For Swift 4:
extension String {
func containsCaseInsensitive(string : String) -> Bool {
return self.localizedCaseInsensitiveContains(string)
}
}
Usage:
print("Hello".containsCaseInsensitive(string: "LLO"))
Output:
true

Check for substring in string with NSString from NSArray?

So pretty much I want to check if my NSString from my NSArray is a substring of my string named imageName.
So lets say this:
My Image name is: picture5of-batman.png
My Array contains strings and one of them is: Batman
So pretty much I want to eliminate the: picture5of- part of the image name and replace it with the NSString from the NSArray.
This is how I try to do it but it never makes it to the if statement. And no my Array is not nil either. Here is the code:
for (NSString *string in superheroArray) {
if ([string rangeOfString:imageName].location != NSNotFound) {
//Ok so some string in superheroArray is equal to the file name of the image
imageName = [imageName stringByReplacingOccurrencesOfString:#"" withString:string
options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];
}
}
Edit1: This still does not work
for (NSString *string in superheroArray) {
if ([imageName rangeOfString:string options:NSCaseInsensitiveSearch].location != NSNotFound) {
//Ok so some string in superheroArray is equal to the file name of the image
imageName = string;
//HOW ABOUT THAT FOR EFFICIENCY :P
}
}
[imageName rangeOfString:string options: NSCaseInsensitiveSearch]
I don't see why it's not working in your code, maybe split the NSString stuff from the NSRage test.
but this work here :
NSArray *ar = [NSArray arrayWithObjects:#"Batman", #"Maurice", nil];
__block NSString *imageName = #"picture5of-batman.png";
__block NSUInteger theIndex = -1;
[ar enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSRange r = [imageName rangeOfString: obj
options: NSCaseInsensitiveSearch];
if (r.location != NSNotFound)
{
theIndex = idx;
NSString *str = [imageName pathExtension];
imageName = [(NSString *)obj stringByAppendingPathExtension:str];
// you found it, so you can stop now
*stop = YES;
}
}];
if (theIndex != -1)
{
NSLog(#"The index is : %d and new imageName == %#", theIndex, imageName);
}
And here is the NSLog statement :
2011-12-10 23:04:28.967 testSwitch1[2493:207] The index is : 0 and new imageName == Batman.png