Check NSMakeRange is Able to take range or Not - iphone

I am currently using the below code to take the substring
NSString *s1 = [stringName substringWithRange: NSMakeRange(0, 2)];
NSString *s2 = [stringName substringWithRange: NSMakeRange(2, 4)];
NSString *s3 = [stringName substringWithRange: NSMakeRange(6, [stringName length])];
Here, how to check the range is valid or not because i am not able to length of string to validate because it may differ on time. Please help me in this issue..

For s3, you're starting at position and ask for exactly as many characters as there are in the string. But since you're starting at position 6, you're asking for 6 characters too many. You need to do:
NSString *s3 = [stringName substringWithRange: NSMakeRange(6, [stringName length] - 6)];

As the apple documentation says ..
substringWithRange:
Returns a string object containing the characters of the receiver that lie within a given range.
- (NSString *)substringWithRange:(NSRange)aRange
aRange
A range. The range must not exceed the bounds of the receiver.
You need to check every time when you construct an NSMakeRange(), whether the Range you specified within the length of your String OR not ... by Using some if and else condition

Related

NSMutableString check last and second last character

I have a NSMutableString. I need to check whether the last character is #":" or last two characters are #": "
How to do that?
Use the hasSuffix: method of NSString.
Identifies last char:
NSString *lastChar = [yourstr substringFromIndex: [yourstr length] - 1];
Identifies last two chars:
NSString *lastTwoChar = [yourstr substringFromIndex: [yourstr length] - 2];

Replace a character in a String iPhone

I want to replace a single character at a particular position in a string.
Example
String: 123-456-7890
Desired Output: 123-406-7890 (Replacing 5 at fifth position with 0)
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
visit here and read all about string
Use stringByReplacingCharactersInRange:withString:, forming the NSRange variable to indicate the 5th position.
NSString *phoneNumber = #"123-456-7890";
NSString *newString = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(5, 1) withString:#"0"];
NSLog(#"%#", newString);
Output: 123-406-7890
Read all about NSString.
for replacing string there are lots of way:
NSString *str = [yourString stringByReplacingOccuranceOfString:#"5" withString:#"0"];
second way first get range of string like:
NSRange range = [yourSting rangeOfString:#"5"];
NSString *first = [yourString substringToIndex:range.location];
NSString *second = [yourString substringFromIndex:range.location+range.length];
NSString *yourNewStr = [NSString stringWithFormat:#"%#0%#",first,second];
Tere are lots of other using string operation but First one is best in that.
Get the range (i.e. index) of first occurrence of the substring.
Then replace at that range with your desired replace value.
NSString *originalString = #"123 456 789";
NSRange r = [originalString rangeOfString:#"5"];
NSString *newString = [originalString stringByReplacingCharactersInRange:r withString:#"0"];
If you want to actually replace the 5th character rather than just any 5 you need to make a range first.
NSRange range = NSMakeRange(5, 1);
NSString *newString = [initialString stringByReplacingCharactersInRange:range withString:#"0"];
Edit: Corrected make range length
you can use :-
NSString *replacechar = #"0";
NSString *newString= [String stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:replacechar];

How do I remove the end of an NSMutableString?

I have the following NSMutableString:
#"1*2*3*4*5"
I want to find the first * and remove everything after it, so my string = #"1"; How do I do this?
NSMutableString *string = [NSMutableString stringWithString:#"1*2*3*4*5"];
NSRange range = [string rangeOfString:#"*"];
if (range.location != NSNotFound)
{
[string deleteCharactersInRange:NSMakeRange(range.location, [string length] - range.location)];
}
You could try to divide this string by a separator and get the first object
NSString *result = [[MyString componentsSeparatedByString:#"*"]objectAtIndex:0];
After calling componentsSeparatedByString:#"*" you'll get the array of strings, separated by *,and the first object is right what you need.
Here's yet another strategy, using the very flexible NSScanner.
NSString* beginning;
NSScanner* scanner = [NSScanner scannerWithString:#"1*2*3*4*5"];
[scanner scanUpToString:#"*" intoString:&beginning];
You could use -rangeOfString: to find the index of the first asterisk and use that with -substringToIndex: to extract a substring from the original input. Something like this perhaps...
NSMutableString *input = #"1*2*3*4*5";
// Finds the range of the first instance. See NSString docs for more options.
NSRange firstAsteriskRange = [input rangeOfString:#"*"];
NSString *trimmedString = [input substringToIndex:firstAsteriskRange.location + 1];

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];

NSString Problem

NSRange rangetxt={0,(index-1)};
NSString *tempStr= textBox.text;
NSString *tempTextBox=[tempStr substringWithRange:rangetxt];
Hi Everyone,
I want to know why my pasted code isn't working properly, when the compiler passes substringWithRange It hung up and do not assign any value to tempTextBox, Secondly I've tried the NSString function substringToIndex as well yet its not working too, My objective is to skip the last character while copying tempStr to tempTextBox.
Regards
MGD
I had test this code and it works:
NSString *strTest = #"Word";
NSRange range = {0, 3};
NSString *strTemp = [strTest substringWithRange: range];
The result: strTemp = "Wor"
So the problem is something else: index is not proper or textBox.text is maybe empty.
Put the breakpoint on your substringWithRange: line and look at the values of index and tempStr before problem appears.
You should use NSMakeRange(loc, len) to create a NSRange object instead of using {}.
You don't show the code that's initialising index. My guess is it's out of range. Note that substringWithRange raises an NSRangeException if any part of the range lies beyond the end of the receiver.
Try this:
NSString *tempStr = textBox.text;
NSRange rangetxt;
if ([tempStr length] > 0)
rangetxt = NSMakeRange(0, [tempStr length] - 1);
else
rangetxt = NSMakeRange(0, 0);
NSString *tempTextBox = [tempStr substringWithRange:rangetxt];
I think i got my problem solved, During the debug when i pass through these line my gdb says "Timed out fetching data. Variable display may be inaccurate" so i found the solution just placed my break point after the initialization of the NSString objects
Thanks for Help Everyone
MGD