I need to determine if a text is an email address, or mobile number, for email address I can use some regular expression, for mobile number I can check if the string has only digits(right?)
and the sequence is like:
is (regex_valid_email(text))
{
// email
}
else if (all_digits(text))
{
// mobile number
}
but how do I check if a string has only numbers in iOS?
Thanks
You create an NSCharacterSet that includes the digits and probably the dash and maybe parentheses (depending on what format you are seeing for the phone numbers). You then invert that set, so you have a set that has everything but those digits and things, then use rangeOfCharactersFromSet and if you get anything but NSNotFound, then you have something other than digits.
This should work:
//This is the input string that is either an email or phone number
NSString *input = #"18003234322";
//This is the string that is going to be compared to the input string
NSString *testString = [NSString string];
NSScanner *scanner = [NSScanner scannerWithString:input];
//This is the character set containing all digits. It is used to filter the input string
NSCharacterSet *skips = [NSCharacterSet characterSetWithCharactersInString:#"1234567890"];
//This goes through the input string and puts all the
//characters that are digits into the new string
[scanner scanCharactersFromSet:skips intoString:&testString];
//If the string containing all the numbers has the same length as the input...
if([input length] == [testString length]) {
//...then the input contains only numbers and is a phone number, not an email
}
Related
i just updated to ios 7 sdk, and I would like to trim/replace the whitespace between characters of a string whereby the numbers are taken out from ABAddressBook.
I have tried using the replace " " with "" code below, but this code doesnt seems to work in ios7 sdk, it works fine in ios 6 sdk by the way.
NSString *TrimmedNumberField = [self.numberField.text
stringByReplacingOccurrencesOfString:#" " withString:#""];
is there any other way I could do it in IOS 7?
EDIT:
It's a phone number type that I'm trying.
Input: "+65 12 345 6789"
The output i got from NSLog is " 12 345 6789"
I realized that when I added into NSDictionary and view it in NSLog, it appears that it contains a unix code representation of \u00a0 which is similar to the "dot in the middle" which is not equals to a fullstop.
thanks in advance.
Found the answer from here
phoneNumber = [phoneNumber stringByReplacingOccurencesOfString:#"." withString:#""];
// where #"." was created by typing Option+ Spacebar
The number is extracted from ABAddressbook.
You can loop over the string and remove whitespace as long as there is any
NSString *someString = #"A string with multiple spaces and other whitespace.";
NSMutableString *mutableCopy = [someString mutableCopy];
// get first occurance of whitespace
NSRange range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
// If there is a match for the whitespace ...
while (range.location != NSNotFound) {
// ... delete it
[mutableCopy deleteCharactersInRange:range];
// and get the next whitespace
range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
}
// no more whitespace. You can get back to an immutable string
someString = [mutableCopy copy];
The result with the string above is Astringwithmultiplespacesandotherwhitespace.
Try This:
NSString *str = #" untrimmed string ";
NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Try This
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
whitespaceCharacterSet Apple Documentation for iOS says
Returns an NSData object encoding the receiver in binary format.
(NSData *)bitmapRepresentation
Return Value
An NSData object encoding the receiver in binary format.
Discussion
This format is suitable for saving to a file or otherwise transmitting or archiving.
A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To test for the presence of a character with decimal Unicode value n in a raw bitmap representation, use an expression such as the following:
So Try This
NSString *testString = #" Eek! There are leading and trailing spaces ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
In my app
i need to know if the first character of a string is a letter or not
Im getting first character of the string like this
NSString *codeString;
NSString *firstLetter = [codeString substringFromIndex:1];
I can know it by comparing with a, b, c, .**.
if([firstLetter isEqualToString "a"] || ([firstLetter isEqualToString "A"] || ([firstLetter isEqualToString "b"] ......)
But is there any other method to know?
I need to display different colors for letters and symbols.
How can i achieve it in simple way?
First off, your line:
NSString *firstLetter = [codeString substringFromIndex:1];
does not get the first letter. This gives you a new string the contains all of the original string EXCEPT the first character. This is the opposite of what you want. You want:
NSString *firstLetter = [codeString substringToIndex:1];
But there is a better way to see if the first character is a letter or not.
unichar firstChar = [[codeString uppercaseString] characterAtIndex:0];
if (firstChar >= 'A' && firstChar <= 'Z') {
// The first character is a letter from A-Z or a-z
}
However, since iOS apps deal with international users, it is far from ideal to simply look for the character being in the letters A-Z. A better approach would be:
unichar firstChar = [codeString characterAtIndex:0];
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
if ([letters characterIsMember:firstChar]) {
// The first character is a letter in some alphabet
}
There are a few cases where this doesn't work as expected. unichar only holds 16-bit characters. But NSString values can actually have some 32-bit characters in them. Examples include many Emoji characters. So it's possible this code can give a false positive. Ideally you would want to do this:
NSRange first = [codeString rangeOfComposedCharacterSequenceAtIndex:0];
NSRange match = [codeString rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first];
if (match.location != NSNotFound) {
// codeString starts with a letter
}
I am using a NSScanner to detect text bound by [square brackets] in a string, and convert it into HTML hyperlinks. I hope to turn convert this text in the following way:
This [is an] example of the [text] I'm using
should convert to
This is an example of the text I'm using
I've implemented a NSScanner, but in order to make it work properly, I need to extract both the first and second of the square brackets.
Here's the current state of my code:
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:stringWithBrackets];
NSString *stringWithoutBrackets;
while ([theScanner isAtEnd] == NO) {
[theScanner scanUpToString:#"[" intoString:NULL];
[theScanner scanUpToString:#"]" intoString:&text];
<BREAK>
At this breakpoint, I have a string returned, which does not contain the closing bracket. So, for the example text string shown above, the contents of NSString *text at the first breakpoint is
[is an
In order to properly manipulate the string, I need to work with both the opening and closing bracket.
Essentially, my question is: how do I advance the NSScanner on one character, and include that character into the variable 'text'?
You can skip the ] character with scanString:
if ([theScanner scanString:#"]" intoString:NULL]) {
text = [text stringByAppendingString:#"]"];
} else {
// Next character is not ']'
}
The else case would only happen if there is no matching ] character. text contains the part from [ to the end of the string in that case.
Alternatively, you could use NSRegularExpression and e.g. the matchesInString method which returns an array of all ranges in the string matching the regular expression.
Whats the best way of detecting a data type from a string in Objective-c?
I'm importing CSV files but each value is just a string.
E.g. How do I tell that "2.0" is a number, "London" should be treated as a category and that "Monday 2nd June" or "2/6/2012" is a date.
I need to test the datatype some how and be confident about which type I use before passing the data downstream.
Regex is the only thing I can think about, but if you are on mac or iphone, than you might try e.g. RegexKitLite
----------UPDATE----------
Instead of my previous suggestion, try this:
NSString *csvString = #"333";
NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,";
NSScanner *typeScanner = [NSScanner scannerWithString: csvString];
[typeScanner setCharactersToBeSkipped: [NSCharacterSet characterSetWithCharactersInString:charSet]];
NSString *checkString = [[NSString alloc] init];
[typeScanner scanString:csvString intoString:&checkString];
if([csvString length] == [checkString length]){
//the string "csvString" is an integer
}
To check for other types (float, string, etc.), change this line (which checks for int type) NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,"; to NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; (which checks for float type) or NSString *charSet = #"1234567890"; (which checks for a string composed only of letters).
-------Initial Post-------
You could do this:
NSString *stringToTest = #"123";
NSCharacterSet *intValueSet = [NSCharacterSet decimalDigitCharacterSet];
NSArray *test = [stringToTest componentsSeparatedByCharactersInSet:intValueSet];
if ([test count]==[stringToTest length]+1){
NSLog(#"It's an int!");
}
else {
NSLog(#"It's not an int");
}
This works for numbers that don't have a decimal point or commas as thousands separators, like "8493" and "883292837". I've tested it and it works.
Hope this provides a start for you! I'll try to figure out how to test for numbers with decimal points and strings.
Like Andrew said, regular expressions are probably good for this, but they're a bit complicated.
I have a NSString object and want to change it into unichar.
int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298
NSString *hex = [NSString stringWithFormat:#"0x%x", decimal]; // hex = 0x300a
NSString *chineseChar = [NSString stringWithFormat:#"%C", hex];
// This statement log a different Chinese char every time I run this code
NSLog(#"%#",chineseChar);
When I see the log, It gives different character every time when I run my code.
m I missing something...?
The %C format specifier takes a 16-bit Unicode character (unichar) as input, not an NSString. You're passing in an NSString, which is getting reinterpreted as an integer character; since the string can be stored at a different address in memory each time you run, you get that address as an integer, which is why you get a different Chinese character every time you run your code.
Just pass in the character as an integer:
unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:#"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET
How about -[NSString characterAtIndex:]? It wants a character index and returns a unichar.