How to test a string for text - iphone

I would like to test a string to see if anywhere it contains the text "hello". I would like the test to not take into account capitalization. How can I test this string?

Use the below code as reference to find check for a substring into a string.
NSString* string = #"How to test a string for text" ;
NSString* substring = #"string for" ;
NSRange textRange;
textRange =[string rangeOfString:substring options:NSCaseInsensitiveSearch];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}

-[NSString rangeOfString: options:] will do it.

NSRange range = [string rangeOfString:#"hello" options:NSCaseInsensitiveSearch];
BOOL notFound = range.location==NSNotFound;

I am assuming all words are separated by a space, and that there is no punctuation. If there is punctuation.
NSArray *dataArray = [inputString componentsSeparatedByString:#" "];
for(int i=0; i<[dataArray count]){
if([[dataArray objectAtIndex:i] isEqualToString:#"hello"]){
NSLog(#"hello has been found!!!");
}
}
I haven't tested this but it should work in theory.
Check out the docs for ways to remove punctuation and make the string all lower case. This should be pretty straight-forward.

Other solutions here are good but you should really use a regex,
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^(hello)*$"
options:NSRegularExpressionCaseInsensitive
error:&error];
Docs are here: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

Related

Replacing instances of a character with two different characters in Objective-C

I have a huge amount of NSStrings in a database that get passed to a view controller in an iOS app. They are formatted as "This is a message with $specially formatted$ content".
However, I need to change the '$' at the start of the special formatting with a '[' and the '$' at the end with ']'. I have a feeling I can use an NSScanner but so far all of my attempts have produced wackily concatenated strings!
Is there a simple way to recognise a substring encapsulated by '$' and swap them out with start/end characters? Please note that a lot of the NSStrings have multiple '$' substrings.
Thanks!
You can use regular expressions:
NSMutableString *str = [#"Hello $World$, foo $bar$." mutableCopy];
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\\$([^$]*)\\$"
options:0
error:NULL];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#"[$1]"];
NSLog(#"%#", str);
// Output:
// Hello [World], foo [bar].
The pattern #"\\$([^$]*)\\$" searches for
$<zero_or_more_characters_which_are_not_a_dollarsign>$
and all occurrences are then replaced by [...]. The pattern contains so many backslashes because the $ must be escaped in the regular expression pattern.
There is also stringByReplacingMatchesInString if you want to create a new string instead of modifying the original string.
I think replaceOccurrencesOfString: won't work cause you have start$ and end$.
But if you seperate the Strings with [string componentsSeperatedByString:#"$"] you get an Array of substrings, so every second string is your "$specially formatted$"-string
This should work!
NSString *str = #"This is a message with $specially formatted$ content";
NSString *original = #"$";
NSString *replacement1 = #"[";
NSString *replacement2 = #"]";
BOOL start = YES;
NSRange rOriginal = [str rangeOfString: original];
while (NSNotFound != rOriginal.location) {
str = [str stringByReplacingCharactersInRange: rOriginal withString:(start?replacement1:replacement2)];
start = !start;
rOriginal = [str rangeOfString: original];
}
NSLog(#"%#", str);
Enjoy Programming!
// string = #"This is a $special markup$ sentence."
NSArray *components = [string componentsSeparatedByString:#"$"];
// sanity checks
if (components.count < 2) return; // maybe no $ characters found
if (components.count % 2) return; // not an even number of $s
NSMutableString *out = [NSMutableString string];
for (int i=0; i< components.count; i++) {
[out appendString:components[i]];
[out appendString: (i % 2) ? #"]" : #"[" ];
}
// out = #"This is a [special markup] sentence."
Try this one
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
NSMutableString *string=[[NSMutableString alloc]initWithString:#"This is a message with $specially formatted$ content. This is a message with $specially formatted$ content"];
BOOL open=YES;
for (NSUInteger i=0; i<[string length];i++) {
if ([string characterAtIndex:i]=='$') {
if (open) {
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"["];
open=!open;
}
else{
[string replaceCharactersInRange:NSMakeRange(i, 1) withString:#"]"];
open=!open;
}
}
}
NSLog(#"-->%#",string);
Output:
-->This is a message with [specially formatted] content. This is a message with [specially formatted] content

Objective-C: Find consonants in string

I have a string that contains words with consonants and vowels. How can I extract only consonants from the string?
NSString *str = #"consonants.";
Result must be:
cnsnnts
You could make a character set with all the vowels (#"aeiouy")
+ (id)characterSetWithCharactersInString:(NSString *)aString
then use the
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
method.
EDIT: This will only remove vowels at the beginning and end of the string as pointed out in the other post, what you could do instead is use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
then stick the components back together. You may also need to include capitalized versions of the vowels in the set, and if you want to also deal with accents (à á è è ê ì etc...) you'll probably have to include that also.
Unfortunately stringByTrimmingCharactersInSet wont work as it only trim leading and ending characters, but you could try using a regular expression and substitution like this:
[[NSRegularExpression
regularExpressionWithPattern:#"[^bcdefghjklmnpqrstvwx]"
options:NSRegularExpressionCaseInsensitive
error:NULL]
stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""]
You probably want to tune the regex and options for your needs.
Possible, for sure not-optimal, solution. I'm printing intermediate results for your learning. Take care of memory allocation (I didn't care). Hopefully someone will send you a better solution, but you can copy and paste this for the moment.
NSString *test = #"Try to get all consonants";
NSMutableString *found = [[NSMutableString alloc] init];
NSInteger loc = 0;
NSCharacterSet *consonants = [NSCharacterSet characterSetWithCharactersInString:#"bcdfghjklmnpqrstvwxyz"];
while(loc!=NSNotFound && loc<[test length]) {
NSRange r = [[test lowercaseString] rangeOfCharacterFromSet:consonants options:0 range:NSMakeRange(loc, [test length]-loc)];
if(r.location!=NSNotFound) {
NSString *temp = [test substringWithRange:r];
NSLog(#"Range: %# Temp: %#",NSStringFromRange(r), temp);
[found appendString:temp];
loc=r.location+r.length;
} else {
loc=NSNotFound;
}
}
NSLog(#"Found: %#",found);
Here is a NSString category that does the job:
- (NSString *)consonants
{
NSString *result = [NSString stringWithString:self];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"aeiou"];
while(1)
{
NSRange range = [result rangeOfCharacterFromSet:characterSet options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
break;
result = [result stringByReplacingCharactersInRange:range withString:#""];
}
return result;
}

NSString search whole text for another string

I would like to search for an NSString in another NSString, such that the result is found even if the second one does not start with the first one, for example:
eg: I have a search string "st". I look in the following records to see if any of the below contains this search string, all of them should return a good result, because all of them have "st".
Restaurant
stable
Kirsten
At the moment I am doing the following:
NSComparisonResult result = [selectedString compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
This works only for "stable" in the above example, because it starts with "st" and fails for the other 2. How can I modify this search so that it returns ok for all the 3?
Thanks!!!
Why not google first?
String contains string in objective-c
NSString *string = #"hello bla bla";
if ([string rangeOfString:#"bla"].location == NSNotFound) {
NSLog(#"string does not contain bla");
} else {
NSLog(#"string contains bla!");
}
Compare is used for testing less than/equal/greater than. You should instead use -rangeOfString: or one of its sibling methods like -rangeOfString:options:range:locale:.
I know this is an old thread thought it might help someone.
The - rangeOfString:options:range: method will allow for case insensitive searches on a string and replace letters like ‘ö’ to ‘o’ in your search.
NSString *string = #"Hello Bla Bla";
NSString *searchText = #"bla";
NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
NSRange searchRange = NSMakeRange(0, string.length);
NSRange foundRange = [string rangeOfString:searchText options:searchOptions range:searchRange];
if (foundRange.length > 0) {
NSLog(#"Text Found.");
}
For more comparison options NSString Class Reference
Documentation on the method - rangeOfString:options:range: can be found on the NSString Class Reference

How to remove whitespace in a string?

I have a string say "Allentown, pa"
How to remove the white space in between , and pa using objective c?
This will remove all space from myString.
NSString *newString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
Here is a proper and documented way of removing white spaces from your string.
whitespaceCharacterSet Apple Documentation for iOS says:
Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
+ (id)whitespaceCharacterSet
Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
Discussion
This set doesn’t contain the newline or carriage return characters.
Availability
Available in iOS 2.0 and later.
You can use this documented way:
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps you.
If you need any more help then please let me know on this.
Probably the solution in one of the answers in Collapse sequences of white space into a single character and trim string:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to white-space and new-line character as well then use "whitespaceAndNewlineCharacterSet" instead of "whitespaceCharacterSet"
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
NSLog(#"Value of the text field is %#",trimmedString);
myStr = [myStr stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *sample = #" string with whitespaces";
NSString *escapeWhiteSpaces = [sample stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)removeWhitespaces {
return [[self componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
}
In my case NSString was added Zero Width Space(i i used some library). so solution worked for me.
NSMutableString *newString=[[newString stringByReplacingOccurrencesOfString:#"\u200B" withString:#""] mutableCopy];
#"\u200B" is Zero width space character value.
Here is the proper way to remove extra whitespaces from string which is coming in between.
NSString *yourString = #"Allentown, pa";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:#" "];
you can use remove function to remove any substring from the string
- (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input {
return [input stringByReplacingOccurrencesOfString:textToRemove withString:#""];
}
I have tried all the solutions here, none of them could remove the whitespace generated by the Chinese PinYin Input method.
After some debugging, I found this working:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\342\200\206" withString:#""];
I have googled what the '\342\200\206' is, but failed.
Whatever, it works for me.
Hi there is the swift version of the solution with extension :
extension String{
func deleteSpaces() -> String{
return self.stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
And Just call
(yourString as! String).deleteSpaces()
Swift 3:
var word: String = "Hello world"
let removeWhiteSpace = word.stringByRemovingWhitespaces
word = "Helloworld"

Detect Phone number in a NSString

I want to extract the phone number from a NSString.
For ex: In the string Call John # 994-456-9966, i want to extract 994-456-9966.
I have tried code like,
NSString *nameRegex =#"(\(\d{3}\)\s?)?\d{3}[-\s\.]\d{4}";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:#"ANY keywords.name CONTAINS[c] %#",nameRegex];
validationResult=[nameTest evaluateWithObject:phoneNo];
but i couldnt get exact result. Can anyone help me? Thanks in advance.
This is what you are looking for, I think:
NSString *myString = #"John # 123-456-7890";
NSString *myRegex = #"\\d{3}-\\d{3}-\\d{4}";
NSRange range = [myString rangeOfString:myRegex options:NSRegularExpressionSearch];
NSString *phoneNumber = nil;
if (range.location != NSNotFound) {
phoneNumber = [myString substringWithRange:range];
NSLog(#"%#", phoneNumber);
} else {
NSLog(#"No phone number found");
}
You can rely on the default Regular Expression search mechanism built into Cocoa. This way you will be able to extract the range corresponding to the phone number, if present.
Remember do alway double-escape backslashes when creating regular expressions.
Adapt your regex accordingly to the part of the phone number you'd like to extract.
Edit
Cocoa provides really simple tools for handling regular expressions. For more complex needs, you should look at the powerful RegexKitLite extension for Cocoa projects.
You can check the official NSDataDetector in iOS 4.0
phoneLinkDetector = [[NSDataDetector alloc] initWithTypes:
(NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber) error:nil];
NSUInteger numberOfPhoneLink = [[self phoneLinkDetector] numberOfMatchesInString:tweet
options:0 range:NSMakeRange(0, tweet.length)];
NSString * number = #"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];
Result: 555555555
if u need just the number u can filter out the special characters and use nsscanner
NSString *numberString = #"Call John # 994-456-9966";
NSString *filteredString=[numberString stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSScanner *aScanner = [NSScanner scannerWithString:filteredString];
[aScanner scanInteger:anInteger];
Assume that you are having "#" symbol in all phone numbers.
NSString *list = #"Call John # 994-456-9966";
NSArray *listItems = [list componentsSeparatedByString:#"#"]
or
You can use the NSScanner to extract the phone number.
EDIT:After seeing the comments.
Assume that you are having only 12 characters in your mobile numbers.
length=get the total length of the string.
index=length-12;
NSString *str=[myString substringFromIndex:index];