NSString is a number? [duplicate] - ios

This question already has answers here:
Check that a input to UITextField is numeric only
(22 answers)
Closed 8 years ago.
I have a TextField and wanted to know if the user just pressed numbers
eg::
_tfNumber.text only has numbers?
is there any function on NSString for this?

This will let you know if all of the characters are numbers:
NSString *originalString = #"1234";
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
NSString * trimmedString = [originalString stringByTrimmingCharactersInSet:numberSet];
if ((trimmedString.length == 0) && (originalString.length > 0)) {
NSLog(#"Original string was all numbers.");
}
Note that this ensures it won't give a false positive for the empty string, which technically also doesn't contain any non-numbers.

try this:
NSCharacterSet *_NumericOnly = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *myStringSet = [NSCharacterSet characterSetWithCharactersInString:mystring];
if ([_NumericOnly isSupersetOfSet: myStringSet]) {
NSLog(#"String has only numbers");
}
I got it from: http://i-software-developers.com/2013/07/01/check-if-nsstring-contains-only-numbers/
You can use this method in your UITextField's delegate method textField:shouldChangeCharactersInRange:replacementString: and do the verification while the user is typing.

No, but it should be easy to write:
- (BOOL)justContainsNumbers:(NSString *)str {
if ([str length] == 0)
return NO;
for (NSUInteger i = 0; i < [str length]; i++)
if (!isdigit([str characterAtIndex:i]))
return NO;
return YES;
}

Let's try regular Expression,
NSString * numberReg = #"[0-9]";
NSPredicate * numberCheck = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberReg];
if ([numberCheck evaluateWithObject:textField.text])
NSLog (#"Number");

No. NSString is not an NSNumber and any values you get from a UITextField will be an NSString. See THIS SO answer for converting that entered NSString value into an NSNumber.

Related

Check if an NSString is a double [duplicate]

This question already has an answer here:
parsing NSString to Double
(1 answer)
Closed 7 years ago.
How do I check if a UITextField's text is a double or not?
Simple validation required, if the entered textfield value is a valid double value or not?
Valid double values: 1.00, 1.01 or 1.00001
Invalid double values: .0.1, .001.11, 1.0.1 or 1...0 etc.
mytxtfield.text=#"12.00"; //ok
mytxtfield.text=#"1.2..0"; // is invalid and so on
EDIT: My answer that works thanx sahzad ali
//------------
-(BOOL)isvalidDouble:(NSString*)txtstring
{
NSArray *dotSeparratedArray = [txtstring componentsSeparatedByString:#"."];
NSInteger count=[dotSeparratedArray count];
count=count-1;
if(count >1)
{
return TRUE ; //invalid
}
return FALSE; //valid
}
You can limit user from entering multiple dots or you can use same logic in your TextFieldDidEndEditing method. If componentsSeparatedByString returns greater than 2 it means there are multiple dots.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *myString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *dotSeparratedArray = [myString componentsSeparatedByString:#"."];
if([dotSeparratedArray count] >= 2)
{
NSString *string1=[NSString stringWithFormat:#"%#",[dotSeparratedArray objectAtIndex:1]];
return !([string1 length]>1);
}
return YES;
}
I don't know whether or not this will serve your purposes, but you could use NSNumberFormatter and customize it to your needs:
NSNumberFormatter *myFormatter = [[NSNumberFormatter alloc] init];
[myFormatter setFormatWidth:7];
[myFormatter setPaddingCharacter:#"0"];
[myFormatter setMinimumSignificantDigits:0];
[myFormatter setMinimum:#0];
[myFormatter setMaximum:#9999999];
[myClientIDTextField setFormatter:myFormatter];

Find substring range of NSString with unicode characters

If I have a string like this.
NSString *string = #"😀1😀3😀5😀7😀"
To get a substring like #"3😀5" you have to account for the fact the smiley face character take two bytes.
NSString *substring = [string substringWithRange:NSMakeRange(5, 4)];
Is there a way to get the same substring by using the actual character index so NSMakeRange(3, 3) in this case?
Thanks to #Joe's link I was able to create a solution that works.
This still seems like a lot of work for just trying to create a substring at unicode character ranges for an NSString. Please post if you have a simpler solution.
#implementation NSString (UTF)
- (NSString *)substringWithRangeOfComposedCharacterSequences:(NSRange)range
{
NSUInteger codeUnit = 0;
NSRange result;
NSUInteger start = range.location;
NSUInteger i = 0;
while(i <= start)
{
result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
codeUnit += result.length;
i++;
}
NSRange substringRange;
substringRange.location = result.location;
NSUInteger end = range.location + range.length;
while(i <= end)
{
result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
codeUnit += result.length;
i++;
}
substringRange.length = result.location - substringRange.location;
return [self substringWithRange:substringRange];
}
#end
Example:
NSString *string = #"😀1😀3😀5😀7😀";
NSString *result = [string substringWithRangeOfComposedCharacterSequences:NSMakeRange(3, 3)];
NSLog(#"%#", result); // 3😀5
Make a swift extension of NSString and use new swift String struct. Has a beautifull String.Index that uses glyphs for counting characters and range selecting. Very usefull is cases like yours with emojis envolved

In objective-c how to get characters after n-th?

I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];

Getting just the phone number digits from kABPersonPhoneProperty in iOS [duplicate]

I have an NSString (phone number) with some parenthesis and hyphens as some phone numbers are formatted. How would I remove all characters except numbers from the string?
Old question, but how about:
NSString *newString = [[origString componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
It explodes the source string on the set of non-digits, then reassembles them using an empty string separator. Not as efficient as picking through characters, but much more compact in code.
There's no need to use a regular expressions library as the other answers suggest -- the class you're after is called NSScanner. It's used as follows:
NSString *originalString = #"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
NSLog(#"%#", strippedString); // "123123123"
EDIT: I've updated the code because the original was written off the top of my head and I figured it would be enough to point the people in the right direction. It seems that people are after code they can just copy-paste straight into their application.
I also agree that Michael Pelz-Sherman's solution is more appropriate than using NSScanner, so you might want to take a look at that.
The accepted answer is overkill for what is being asked. This is much simpler:
NSString *pureNumbers = [[phoneNumberString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:#""];
This is great, but the code does not work for me on the iPhone 3.0 SDK.
If I define strippedString as you show here, I get a BAD ACCESS error when trying to print it after the scanCharactersFromSet:intoString call.
If I do it like so:
NSMutableString *strippedString = [NSMutableString stringWithCapacity:10];
I end up with an empty string, but the code doesn't crash.
I had to resort to good old C instead:
for (int i=0; i<[phoneNumber length]; i++) {
if (isdigit([phoneNumber characterAtIndex:i])) {
[strippedString appendFormat:#"%c",[phoneNumber characterAtIndex:i]];
}
}
Though this is an old question with working answers, I missed international format support. Based on the solution of simonobo, the altered character set includes a plus sign "+". International phone numbers are supported by this amendment as well.
NSString *condensedPhoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:
[[NSCharacterSet characterSetWithCharactersInString:#"+0123456789"]
invertedSet]]
componentsJoinedByString:#""];
The Swift expressions are
var phoneNumber = " +1 (234) 567-1000 "
var allowedCharactersSet = NSMutableCharacterSet.decimalDigitCharacterSet()
allowedCharactersSet.addCharactersInString("+")
var condensedPhoneNumber = phoneNumber.componentsSeparatedByCharactersInSet(allowedCharactersSet.invertedSet).joinWithSeparator("")
Which yields +12345671000 as a common international phone number format.
Here is the Swift version of this.
import UIKit
import Foundation
var phoneNumber = " 1 (888) 555-5551 "
var strippedPhoneNumber = "".join(phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))
Swift version of the most popular answer:
var newString = join("", oldString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))
Edit: Syntax for Swift 2
let newString = oldString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
Edit: Syntax for Swift 3
let newString = oldString.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
Thanks for the example. It has only one thing missing the increment of the scanLocation in case one of the characters in originalString is not found inside the numbers CharacterSet object. I have added an else {} statement to fix this.
NSString *originalString = #"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:originalString.length];
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
}
// --------- Add the following to get out of endless loop
else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
// --------- End of addition
}
NSLog(#"%#", strippedString); // "123123123"
It Accept only mobile number
NSString * strippedNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [mobileNumber length])];
It might be worth noting that the accepted componentsSeparatedByCharactersInSet: and componentsJoinedByString:-based answer is not a memory-efficient solution. It allocates memory for the character set, for an array and for a new string. Even if these are only temporary allocations, processing lots of strings this way can quickly fill the memory.
A memory friendlier approach would be to operate on a mutable copy of the string in place. In a category over NSString:
-(NSString *)stringWithNonDigitsRemoved {
static NSCharacterSet *decimalDigits;
if (!decimalDigits) {
decimalDigits = [NSCharacterSet decimalDigitCharacterSet];
}
NSMutableString *stringWithNonDigitsRemoved = [self mutableCopy];
for (CFIndex index = 0; index < stringWithNonDigitsRemoved.length; ++index) {
unichar c = [stringWithNonDigitsRemoved characterAtIndex: index];
if (![decimalDigits characterIsMember: c]) {
[stringWithNonDigitsRemoved deleteCharactersInRange: NSMakeRange(index, 1)];
index -= 1;
}
}
return [stringWithNonDigitsRemoved copy];
}
Profiling the two approaches have shown this using about 2/3 less memory.
You can use regular expression on mutable string:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
#"[^\\d]"
options:0
error:nil];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, str.length)
withTemplate:#""];
Built the top solution as a category to help with broader problems:
Interface:
#interface NSString (easyReplace)
- (NSString *)stringByReplacingCharactersNotInSet:(NSCharacterSet *)set
with:(NSString *)string;
#end
Implemenation:
#implementation NSString (easyReplace)
- (NSString *)stringByReplacingCharactersNotInSet:(NSCharacterSet *)set
with:(NSString *)string
{
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:self.length];
NSScanner *scanner = [NSScanner scannerWithString:self];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:set intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
[strippedString appendString:string];
}
}
return [NSString stringWithString:strippedString];
}
#end
Usage:
NSString *strippedString =
[originalString stringByReplacingCharactersNotInSet:
[NSCharacterSet setWithCharactersInString:#"01234567890"
with:#""];
Swift 3
let notNumberCharacters = NSCharacterSet.decimalDigits.inverted
let intString = yourString.trimmingCharacters(in: notNumberCharacters)
swift 4.1
var str = "75003 Paris, France"
var stringWithoutDigit = (str.components(separatedBy:CharacterSet.decimalDigits)).joined(separator: "")
print(stringWithoutDigit)
Um. The first answer seems totally wrong to me. NSScanner is really meant for parsing. Unlike regex, it has you parsing the string one tiny chunk at a time. You initialize it with a string, and it maintains an index of how far along the string it's gotten; That index is always its reference point, and any commands you give it are relative to that point. You tell it, "ok, give me the next chunk of characters in this set" or "give me the integer you find in the string", and those start at the current index, and move forward until they find something that doesn't match. If the very first character already doesn't match, then the method returns NO, and the index doesn't increment.
The code in the first example is scanning "(123)456-7890" for decimal characters, which already fails from the very first character, so the call to scanCharactersFromSet:intoString: leaves the passed-in strippedString alone, and returns NO; The code totally ignores checking the return value, leaving the strippedString unassigned. Even if the first character were a digit, that code would fail, since it would only return the digits it finds up until the first dash or paren or whatever.
If you really wanted to use NSScanner, you could put something like that in a loop, and keep checking for a NO return value, and if you get that you can increment the scanLocation and scan again; and you also have to check isAtEnd, and yada yada yada. In short, wrong tool for the job. Michael's solution is better.
For those searching for phone extraction, you can extract the phone numbers from a text using NSDataDetector, for example:
NSString *userBody = #"This is a text with 30612312232 my phone";
if (userBody != nil) {
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
NSArray *matches = [detector matchesInString:userBody options:0 range:NSMakeRange(0, [userBody length])];
if (matches != nil) {
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypePhoneNumber) {
DbgLog(#"Found phone number %#", [match phoneNumber]);
}
}
}
}
`
I created a category on NSString to simplify this common operation.
NSString+AllowCharactersInSet.h
#interface NSString (AllowCharactersInSet)
- (NSString *)stringByAllowingOnlyCharactersInSet:(NSCharacterSet *)characterSet;
#end
NSString+AllowCharactersInSet.m
#implementation NSString (AllowCharactersInSet)
- (NSString *)stringByAllowingOnlyCharactersInSet:(NSCharacterSet *)characterSet {
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:self.length];
NSScanner *scanner = [NSScanner scannerWithString:self];
while (!scanner.isAtEnd) {
NSString *buffer = nil;
if ([scanner scanCharactersFromSet:characterSet intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
scanner.scanLocation = scanner.scanLocation + 1;
}
}
return strippedString;
}
#end
I think currently best way is:
phoneNumber.replacingOccurrences(of: "\\D",
with: "",
options: String.CompareOptions.regularExpression)
If you're just looking to grab the numbers from the string, you could certainly use regular expressions to parse them out. For doing regex in Objective-C, check out RegexKit. Edit: As #Nathan points out, using NSScanner is a much simpler way to parse all numbers from a string. I totally wasn't aware of that option, so props to him for suggesting it. (I don't even like using regex myself, so I prefer approaches that don't require them.)
If you want to format phone numbers for display, it's worth taking a look at NSNumberFormatter. I suggest you read through this related SO question for tips on doing so. Remember that phone numbers are formatted differently depending on location and/or locale.
Swift 5
let newString = origString.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
Based on Jon Vogel's answer here it is as a Swift String extension along with some basic tests.
import Foundation
extension String {
func stringByRemovingNonNumericCharacters() -> String {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
}
}
And some tests proving at least basic functionality:
import XCTest
class StringExtensionTests: XCTestCase {
func testStringByRemovingNonNumericCharacters() {
let baseString = "123"
var testString = baseString
var newString = testString.stringByRemovingNonNumericCharacters()
XCTAssertTrue(newString == testString)
testString = "a123b"
newString = testString.stringByRemovingNonNumericCharacters()
XCTAssertTrue(newString == baseString)
testString = "a=1-2_3#b"
newString = testString.stringByRemovingNonNumericCharacters()
XCTAssertTrue(newString == baseString)
testString = "(999) 999-9999"
newString = testString.stringByRemovingNonNumericCharacters()
XCTAssertTrue(newString.characters.count == 10)
XCTAssertTrue(newString == "9999999999")
testString = "abc"
newString = testString.stringByRemovingNonNumericCharacters()
XCTAssertTrue(newString == "")
}
}
This answers the OP's question but it could be easily modified to leave in phone number related characters like ",;*#+"
NSString *originalPhoneNumber = #"(123) 123-456 abc";
NSCharacterSet *numbers = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
NSString *trimmedPhoneNumber = [originalPhoneNumber stringByTrimmingCharactersInSet:numbers];
];
Keep it simple!

Extracting from the right of a string in objective C [duplicate]

This question already has answers here:
Get last 2 characters of a string?
(2 answers)
Closed 9 years ago.
This seems to be what I'm looking for but in reverse. I would like the string to extract from the right not from the left.
The example extracting from the left is given:
NSString *source = #"0123456789";
NSString *firstFour = [source substringToIndex:4];
Output: "0123"
I'm looking for a version of the below that works from the right (what is below doesn't work)
NSString *source = #"0123456789";
NSString *lastFour = [source substringToIndex:-4];
Output: "6789"
the [source substringFromIndex:6]; won't work because sometimes I will get an answer that is 000123456789 or 456789 or 6789. In all cases I just need the last 4 characters from the string so that I can convert it to a number.
there must be a better way than a bunch of if else statements?
As you are not sure, about the length of the string, so you must check it before extracting like this:
NSString *source = #"0123456789";
NSNumber *number;
if (source.length>=4) {
NSString *lastFour=[source substringFromIndex:source.length-4];
number=#([lastFour integerValue]); //and save it in a number, it can be int or NSInteger as per your need
}
NSLog(#"%#",number);
Also if you want a quick method that you need to call several times, create a category :
#implementation NSString (SubstringFromRight)
-(NSString *)substringFromRight:(NSUInteger)from{
if (self.length<from) {
return nil;
}
return [self substringFromIndex:self.length-from];
}
#end
And use it as :NSLog(#"%#",[source1 substringFromRight:4]);
NSString *source = #"0123456789";
NSString *newString = [source substringFromIndex:[source length] - 4];
NSLog(#"%#",newString);
replace
NSString *lastFour = [source substringToIndex:-4];
with
NSString *lastFour = [source substringFromIndex:[source length] - 4];
which returns you the last 4 characters of your original string string in lastFour string.
You can use the following code to get last 4 characters from your string.
NSString *last4Characters = [source substringFromIndex:(source.length - 4)];
NSLog(#"Last 4 Characters:%#",last4Characters);
last4Characters=nil;
Please let me know if any issue.

Resources