Check if the entered text uses only English letters - iphone

I am working on an iPhone application and need to make sure the entered text is composed of only a to z and numbers.
I don't want the user to use other languages letters like those with accents or dots above them.
EDIT: I am new to this RegEx, so if you please give me a code or a link, i will be really thankful.

Use a regular expression, like [0-9a-zA-Z]+. Check out the RegexKit Framework for Objective C, a regular expression library that works on the iPhone.
You can then do something like:
NSString *str = #"abc0129yourcontent";
BOOL isMatch = [str isMatchedByRegex:#"^[0-9a-zA-Z]+$"];

One more approach (may be not so elegant as with RegEx):
NSCharacterSet* tSet = [NSCharacterSet characterSetWithCharactersInString:
#"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSCharacterSet* invSet = [tSet invertedSet];
NSString* legalS = #"abcdA1";
NSString* illegalS = #"asvéq1";
if ([legalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
NSLog(legalS); // not printed
if ([illegalS rangeOfCharacterFromSet:invSet].location != NSNotFound)
NSLog(illegalS); // printed

The simplest way - assuming you want to allow for punctuation as well is to check that all the characters are between ascii values 32 (space) and 126 (~). The ASCII table illustrates the point.
All the accented characters are what we used to call "high" ascii when I first started programming.
If you don't want to allow punctuation you'll have to do several range checks:
48 to 57 for numbers
65 to 90 for upper case
97 to 122 for lower case
which might make the RegEx approach more readable (I can't believe I just wrote that)

Easy implementation (take from above, edited just for fast copy-paste):
Objective-C:
BOOL onlyEnglishAlphanumerical = ([self.textField.text rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet]].location == NSNotFound);
self.textField.layer.borderWidth = (onlyEnglishAlphanumerical) ? 0 : 1;
if (onlyEnglishAlphanumerical)
{
//Do the deal
}
Swift:
if (self.textField.text.rangeOfCharacterFromSet(NSCharacterSet.init(charactersInString:"abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet) == nil)
{
//Do the deal
}

Related

UITextView right to left Unicode \u202B not working

I am essentially making a teleprompter app and I need a UITextView to display right to left for EVERY line.
NSString *textString = #"Hello There\nMy name is Mark";
textView.text = [#"\u202B" stringByAppendingString: textString];
This is not working. I need this to read
" erehT olleH"
" kraM si eman yM"
I understand that I also need fonts that are upside down etc.. I need to get this part fixed first. Thanks.
The notation \u202b denotes the Unicode character U+202B is RIGHT-TO-LEFT EMBEDDING, which does not affect the writing direction of characters with strong directionality, such as Latin letters.
The character U+202E RIGHT-TO-LEFT OVERRIDE (\u202e) forces right-to-left writing direction, overriding the inherent directionality of characters. To end its effect, use the U+202C POP DIRECTIONAL FORMATTING character:
'\u202eHello There\nMy name is Mark \u202c'
This has little to do with fonts. The rendering engine is supposed to handle some characters like “(” using mirrored symbols, e.g. so that “(foo)” gets rendered as “(oof)” and not “)oof(” in right-to-left writing. But generally, no mirroring is involved; letters remain the same, they just run right to left.
If you actually want to have text mirrored, you need something completely different (a transformation).
This is the logic for reversing the string... I hope this helps you... Just append this string in your textView.text
NSString *sampleString = #"Hello this is sample \n Hello there";
NSMutableString *reverseString = [NSMutableString string];
NSInteger index = [sampleString length];
while (index > 0)
{
index--;
NSRange subStrRange = NSMakeRange(index, 1);
[reverseString appendString:[sampleString substringWithRange:subStrRange]];
}
NSLog(#"%#", reverseString);

How can I create a string from just the first line of my UITextView?

I am making a UITextView which is similar to notes.app, where the first line of the textView is used as the title. I need to create a new string which contains only the first line of text. So far I've come up with this:
NSRange startRange = NSMakeRange(0, 1);
NSRange titleRange = [noteTextView.text lineRangeForRange:startRange];
NSString *titleString = [noteTextView.text substringToIndex:titleRange.length];
NSLog(#"The title is: %#", titleString);
The only problem with this is that it relies on the user pressing Return. I've also tried using a loop to find the number of characters in the first line:
CGSize lineSize = [noteTextView.text sizeWithFont:noteTextView.font
constrainedToSize:noteTextView.frame.size
lineBreakMode:UILineBreakModeWordWrap];
int textLength =1;
while ((lineSize.width < noteTextView.frame.size.width) &&
([[noteTextView.text substringToIndex:textLength] length] < [noteTextView.text length]))
{
lineSize = [[noteTextView.text substringToIndex:textLength] sizeWithFont:noteTextView.font
constrainedToSize:noteTextView.frame.size
lineBreakMode:UILineBreakModeWordWrap];
textLength = textLength+1;
}
NSLog(#"Length is %i", textLength);
But I've got this wrong somewhere - it returns the total number of characters, instead of the number on the first line.
Does anyone know an easier/better way of doing this?
There is probably a much better way with CoreText, but I'll throw this out there just because it came to mind off the top of my head.
You could add characters one by one to an NSMutableString *title while
[title sizeWithFont:noteTextView.font].width < noteTextView.frame.size.width
then drop the last one, obviously doing the necessary bounds checking along the way and dropping the last added character if necessary.
But sizeWithFont is sloooooow. So if you're doing this often you might want to consider another definition of 'title' - say, at first word break after 20 chars.
But again, CoreText might yield more possibilities.
I do not understand the code you're having above. Wouldn't it be simpler do just find the first line of text in the string, e.g. until a CR or LF terminates the first line?
And if there is no CR or LF, then you take the entire text as you have only one line then.
Of course, this will give you not what is visible in the first line in case the line is longer and gets wrapped, but I think that using lineRangeForRange doesn't do this, either, or does it?
And if your only concern is that "the user has to press enter" to make it work, then why not simply append a newline char to the text before testing for the first line's length?
See how many characters can fit in one line of your text view and use that number in a substringToIndex: method. Like this:
Type out the same character repeatedly and count how many fit in one line. Make sure to use a wide letter to ensure reliability. Use a capital g or m or q or w or whatever is widest in the font you're using.
Say 20 characters can fit in one line.
Then do
NSString *textViewString = notesTextView.text;
NSString *titleString = [textViewString substringToIndex:20]
Just use the titleString as the title.

Is It Possible To Increment A Letter, i.e A + 1 = B In Objective-C?

I am used to doing this in C or C++, ie:
myChar++;
should increment a letter.
I am trying to do the same in Objective-C, except that I have a NSString to start off with (the NSString is always just one letter). I have tried converting the NSString to a char *, but this method is deprecated and other ways of achieving this don't seem to work.
How should I convert an NSString to a char * - or, is there a way to increment a character in objective-c without needing a char * somehow?
Thanks :)
// Get the first character as a UTF-16 (2-byte) character:
unichar c = [string characterAtIndex:0];
// Increment as usual:
c++;
// And to turn it into a 1-character string again:
[NSString stringWithCharacters:&c length:1];
Of course, this assumes incrementing a Unicode character makes sense, which does for ASCII-range characters but probably not for others.
How about NSString's
- (unichar)characterAtIndex:(NSUInteger)index;
Would that work?

How to find and replace symbols in a string?

I know it must be a very simple thing to do but I've never had to treat strings before (in Objective-C) and apparently there's not RegEx on Cocoa-Touch.
Well, the situation is:
I have a text field to get a value (money, such as 32.10 for instance).
The problem:
If the user types in a symbol such as #, /, # etc. my app will crash.
The Question: How can I treat this string to remove the symbols if there are any?
you can try this:
NSString *s = #"12.827##584";
NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:#"/:##"];
s = [[s componentsSeparatedByCharactersInSet: removeCharSet] componentsJoinedByString: #""];
NSLog(#"%#", s);
You do get regex in Cocoa Touch.
Here's a good discussion of the varying degrees of regex power in iOS, the blocks example at the end should get you most of the way there.
http://volonbolon.net/post/861427732/text-handling-in-ios-4
I understand you're trying to figure out the number included in the UITextFields's text property and assign it to a float variable.
Try using an NSScanner for this:
NSScanner* textScanner = [NSScanner localizedScannerWithString:textfield.text];
float* floatValue;
[textScanner scanFloat:&floatValue];
floatValue now contains the parsed float value of your textfield.

How can I detect if a string contains punctuation marks at the end?

Lets assume I have the string:
"Hello I like your shoes #today...!"
I am tokenizing the string by spaces:
return [string componentsSeparatedByString:#" "];
So my array contains:
Hello
I
like
your
shoes
#today...!
I want to focus on "#today...!" any word that has a # in the prefix I am changing the font color.
How can I make sure that only "#today" has its font color changed?
I would basically like to figure out if a word has a punctuation mark at the end, and change the color for characters before the punctuation mark.
I'm confused by your question. Are you trying to detect string with punctuation marks at the end or with # marks at the beginning?
In any case:
for (NSString *word in [string componentsSeparatedByString:#" "]) {
if ([word hasPrefix:#"#"])NSLog(#"%# starts with #",word);
if ([word hasSuffix:#"!"])NSLog(#"%# end with !",word);
}
You could do something like:
if ([[NSCharacterSet symbolCharacterSet] characterIsMember:[word characterAtIndex:0]]) NSLog(#"%#", word);
This is to test for a symbol at the beginning of the string--to test at the end, you would use [word characterAtIndex:([word length] - 1)]
EDIT: OK, I think I understand the question now. If you want want to only change the color of characters before the color set, you could do something along the lines of:
NSRange punctCharRange = [word rangeOfCharacterFromSet:[NSCharacterSet punctuationCharacterSet]];
for (int i = 0; i < punctCharRange.location; i++) {
//change the color of the character
}
Consider using RegexKitLite and this method:
- (NSRange)rangeOfRegex:(NSString *)regex
options:(RKLRegexOptions)options
inRange:(NSRange)range
capture:(NSInteger)capture
error:(NSError **)error;
The regex you'd want is something like #"#\\S+\\b". This regex says "Find a '#' character followed by 1 or more non-space characters followed by a word boundary".
This would then return the range of the matched regex inside the string to match.
The following code should look from the end of word toward the beginning until it finds a character that is not alphanumeric, test if it found such a character and if so, remove anything after that character. (untested code)
NSString *wordWithoutTrailingNonAlphanum;
NSRange firstNonAlphanumCharFromEnd =
[word rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]
options:NSBackwardsSearch];
if (firstNonAlphanumCharFromEnd.location != NSNotFound) {
wordWithoutTrailingNonAlphanum =
[word substringToIndex:(firstNonAlphanumCharFromEnd.location + 1)];
}
I tried tokenizing all words that begin with # and splitting it based on the NSPunctuationCharacterSet. This works, however I lose the punctuation marks.