How to check the NSString contains the '%' or not? - iphone

I want to ask a question about the objective C. Does the NSString * contains some functions to check the NSString * contains some string in the UITextField.text? For example
NSString *checkString = #"abcd%"
if(checkString contains '%') // I want this function
return YES;
else
return NO;

if([checkString rangeOfString:#"%"].location != NSNotFound)
// hooray!

You can use - (NSRange)rangeOfString:(NSString *)aString. The code will look something like:
NSRange range = [UITextField.text rangeOfString:#"!"];
if (range.length > 0){
NSLog(#"String contains '!'");
}
else {
NSLog(#"No '!' found in string");
}

The code from the previous post is not correct
NSRange range = [UITextField.text rangeOfString:#"!"];
if (range.length >= 0){
NSLog(#"String contains '!'");
}
else {
NSLog(#"No '!' found in string");
}
It should be "range.length > 0"

Related

How can i remove all emojs from a NSString

I need to remove all emoijs from a NSString.
So far i am using this NSString extension ...
- (NSString*)noEmoticon {
static NSMutableCharacterSet *emoij = NULL;
if (emoij == NULL) {
emoij = [[NSMutableCharacterSet alloc] init];
// unicode range of old emoijs
[emoij removeCharactersInRange:NSMakeRange(0xE000, 0xE537 - 0xE000)];
}
NSRange range = [self rangeOfCharacterFromSet:emoij];
if (range.length == 0) {
return self;
}
NSMutableString *cleanedString = [self mutableCopy];
while (range.length > 0) {
[cleanedString deleteCharactersInRange:range];
range = [cleanedString rangeOfCharacterFromSet:emoij];
}
return cleanedString;
}
... but that does not work at all. The range.length is always 0.
So the general question is : How can i remove a range of unicode characters from a NSString?
Thanks a lot.
It seems to me that in the above code the emoij variable is eventually an empty set. Didn't you mean to addCharactersInRange: rather than to removeCharactersInRange:?

Condition for checking NOT <null> value for NSString in Objective C

Code:
NSString *tempPhone = [NSString stringWithFormat:#"%#", [personDict objectForKey:kPhoneKey]];
NSLog(#"NSString *tempPhone = %#",tempPhone);
Output:
NSString *tempPhone = <null>
Now I want to add if condition, for not null; I tried followings:
if (tempEmail != NULL)
if (tempPhone != Nil)
if (tempPhone != nil)
if (![tempPhone compare:#"<null>"])
if (tempPhone != (NSString*)[NSNull null])
I also Checked this Post.
None of them is working for me. Where I am going wrong??
Try the following code
id phoneNo = [personDict objectForKey:kPhoneKey];
if( phoneNo && ![phoneNo isKindOfClass:[NSNull class]] )
{
NSString *tempPhone = [NSString stringWithFormat:#"%#", [personDict objectForKey:kPhoneKey]];
NSLog(#"NSString *tempPhone = %#",tempPhone);
}
else
{
NSLog(#"NSString *tempPhone is null");
}
I think your personDict does not have an object for the key kPhoneKey, so it is returning nil. When you format nil using %#, you get the string "(null)".
id object = [personDict objectForKey:kPhoneKey];
if (object) {
NSString *tempPhone = [NSString stringWithFormat:#"%#", object];
NSLog(#"NSString *tempPhone = %#",tempPhone);
} else {
// object is nil
}
if (tempPhone != nil || [tempPhone isEqualToString:#"(null)"])
Works for me.
It's like this :
if (![tempPhone isKindOfClass:[NSNull class]] && tempPhone != nil)
if ([str_name isKindOfClass:[NSNull class]])
works for me...
I Checked the webResponse (JSON, in my case).
It was returning me the string with value:
<null>
So, The following condition worked for me:
if (![tempPhone isEqualToString:#"<null>"])
Thanks for all your time. Thanks.
Because compare method returns type NSComparisonResult which is defined as
enum _NSComparisonResult {NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending};
typedef NSInteger NSComparisonResult;
If the string is the same, it will return NSOrderedSame which have a NSInteger value of 0.
Thus, the following line actually means...
if (![tempPhone compare:#"<null>"]) // `tempPhone` is equals to `#"<null>"`
or in a more understandable explanation, if tempPhone value is equal to #"<null>".
You should write it as
if ([tempPhone compare:#"<null>"] != NSOrderedSame)
or
if (![tempPhone isEqualString:#"<null>"])
In case the string is having a null value. Example in NSLog.. Implement this way..
if ([StringName isKindOfClass:[NSNULL Class]]) {
}
else {
}
First we need to check string length.
if (tempPhone.length == 0)
`
{
//Your String is having empty value (E.x, (null))
}
else
{
// You having some values in this string
}`

How to check if a string contains an URL

i have text message and I want to check whether it is containing text "http" or URL exists in that.
How will I check it?
NSString *string = #"xxx http://someaddress.com";
NSString *substring = #"http:";
Case sensitive example:
NSRange textRange = [string rangeOfString:substring];
if(textRange.location != NSNotFound){
//Does contain the substring
}else{
//Does not contain the substring
}
Case insensitive example:
NSRange textRange = [[string lowercaseString] rangeOfString:[substring lowercaseString]];
if(textRange.location != NSNotFound){
//Does contain the substring
}else{
//Does not contain the substring
}
#Cyprian offers a good option.
You could also consider using a NSRegularExpression which would give you far more flexibility assuming that's what you need, e.g. if you wanted to match http:// and https://.
Url usually has http or https in it
You can use your custom method containsString to check for those strings.
- (BOOL)containsString:(NSString *)string {
return [self containsString:string caseSensitive:NO];
}
- (BOOL)containsString:(NSString*)string caseSensitive:(BOOL)caseSensitive {
BOOL contains = NO;
if (![NSString isNilOrEmpty:self] && ![NSString isNilOrEmpty:string]) {
NSRange range;
if (!caseSensitive) {
range = [self rangeOfString:string options:NSCaseInsensitiveSearch];
} else {
range = [self rangeOfString:string];
}
contains = (range.location != NSNotFound);
}
return contains;
}
Example :
[yourString containsString:#"http"]
[yourString containsString:#"https"]

NSString is empty

How do you test if an NSString is empty? or all whitespace or nil? with a single method call?
You can try something like this:
#implementation NSString (JRAdditions)
+ (BOOL)isStringEmpty:(NSString *)string {
if([string length] == 0) { //string is empty or nil
return YES;
}
if(![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
//string is all whitespace
return YES;
}
return NO;
}
#end
Check out the NSString reference on ADC.
This is what I use, an Extension to NSString:
+ (BOOL)isEmptyString:(NSString *)string;
// Returns YES if the string is nil or equal to #""
{
// Note that [string length] == 0 can be false when [string isEqualToString:#""] is true, because these are Unicode strings.
if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
return YES;
}
string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([string isEqualToString:#""]) {
return YES;
}
return NO;
}
I use,
+ (BOOL ) stringIsEmpty:(NSString *) aString {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
} else {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
}
if (cleanWhileSpace) {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
I hate to throw another log on this exceptionally old fire, but I'm leery about editing someone else's answer - especially when it's the selected answer.
Jacob asked a follow up question: How can I do this with a single method call?
The answer is, by creating a category - which basically extends the functionality of a base Objective-C class - and writing a "shorthand" method for all the other code.
However, technically, a string with white space characters is not empty - it just doesn't contain any visible glyphs (for the last couple of years I've been using a method called isEmptyString: and converted today after reading this question, answer, and comment set).
To create a category go to Option+Click -> New File... (or File -> New -> File... or just command+n) -> choose Objective-C Category. Pick a name for the category (this will help namespace it and reduce possible future conflicts) - choose NSString from the "Category on" drop down - save the file somewhere. (Note: The file will automatically be named NSString+YourCategoryName.h and .m.)
I personally appreciate the self-documenting nature of Objective-C; therefore, I have created the following category method on NSString modifying my original isEmptyString: method and opting for a more aptly declared method (I trust the compiler to compress the code later - maybe a little too much).
Header (.h):
#import <Foundation/Foundation.h>
#interface NSString (YourCategoryName)
/*! Strips the string of white space characters (inlcuding new line characters).
#param string NSString object to be tested - if passed nil or #"" return will
be negative
#return BOOL if modified string length is greater than 0, returns YES;
otherwise, returns NO */
+ (BOOL)visibleGlyphsExistInString:(NSString *)string;
#end
Implementation (.m):
#implementation NSString (YourCategoryName)
+ (BOOL)visibleGlyphsExistInString:(NSString *)string
{
// copying string should ensure retain count does not increase
// it was a recommendation I saw somewhere (I think on stack),
// made sense, but not sure if still necessary/recommended with ARC
NSString *copy = [string copy];
// assume the string has visible glyphs
BOOL visibleGlyphsExist = YES;
if (
copy == nil
|| copy.length == 0
|| [[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
) {
// if the string is nil, no visible characters would exist
// if the string length is 0, no visible characters would exist
// and, of course, if the length after stripping the white space
// is 0, the string contains no visible glyphs
visibleGlyphsExist = NO;
}
return visibleGlyphsExist;
}
#end
To call the method be sure to #import the NSString+MyCategoryName.h file into the .h or .m (I prefer the .m for categories) class where you are running this sort of validation and do the following:
NSString* myString = #""; // or nil, or tabs, or spaces, or something else
BOOL hasGlyphs = [NSString visibleGlyphsExistInString:myString];
Hopefully that covers all the bases. I remember when I first started developing for Objective-C the category thing was one of those "huh?" ordeals for me - but now I use them quite a bit to increase reusability.
Edit: And I suppose, technically, if we're stripping characters, this:
[[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
Is really all that is needed (it should do everything that category method does, including the copy), but I could be wrong on that score.
I'm using this define as it works with nil strings as well as empty strings:
#define STR_EMPTY(str) \
str.length == 0
Actually now its like this:
#define STR_EMPTY(str) \
(![str isKindOfClass:[NSString class]] || str.length == 0)
Maybe you can try something like this:
+ (BOOL)stringIsEmpty:(NSString *)str
{
return (str == nil) || (([str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]).length == 0);
}
Based on the Jacob Relkin answer and Jonathan comment:
#implementation TextUtils
+ (BOOL)isEmpty:(NSString*) string {
if([string length] == 0 || ![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
return YES;
}
return NO;
}
#end
Should be easier:
if (![[string stringByReplacingOccurencesOfString:#" " withString:#""] length]) { NSLog(#"This string is empty"); }

iPhone 'Whole Word' Search

I am currently using the following algorithm to search on my iPhone app:
NSRange range = [entry.englishEntry rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
{
[self.filteredListContent addObject:entry];
}
The problem is that when I search for a word like 'crap' I also get results for words like 'scrap' which is irrelevant. I am unfamiliar with NSRange so what is the search algorithm for searching the whole word?
I just solved this problem by adding a simple category on NSString to do a word boundary search. Here's the code:
#interface NSString (FullWordSearch)
// Search for a complete word. Does not match substrings of words. Requires fullWord be present
// and no surrounding alphanumeric characters.
- (BOOL)containsFullWord:(NSString *)fullWord;
#end
#implementation NSString (FullWordSearch)
- (BOOL)containsFullWord:(NSString *)fullWord {
NSRange result = [self rangeOfString:fullWord];
if (result.length > 0) {
if (result.location > 0 && [[NSCharacterSet alphanumericCharacterSet] characterIsMember:[self characterAtIndex:result.location - 1]]) {
// Preceding character is alphanumeric
return NO;
}
if (result.location + result.length < [self length] && [[NSCharacterSet alphanumericCharacterSet] characterIsMember:[self characterAtIndex:result.location + result.length]]) {
// Trailing character is alphanumeric
return NO;
}
return YES;
}
return NO;
}
#end
Yes you can search within words. You need to split the string into components first. Then loop through each one and compare them.
Something like that:
NSArray *words = [entry.english componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in words)
{
NSComparisonResult result = [word compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:entry];
break;
}
}
Instead of finding the range of a string, just do a case-insensitive compare and check if the result is NSOrderedSame
if([entry.english caseInsensitiveCompare:searchText] == NSOrderedSame){
[self.filteredListContent addObject:entry];
}
This will compare the text with the whole word and not just look for the range.
Now i make it as more generic, by using this code you can search any string between target string
NSString * strName =[entry.english lowercaseString];
if ([strName rangeOfString:[searchText lowercaseString]].location != NSNotFound) {
[self.filteredListContent addObject:entry];}