Checking for multiple characters in nsstring - iphone

i have a string and i want to check for the multiple characters in this string the following code i working fine for one character how to check for the multiple characters.
NSString *yourString = #"ABCCDEDRFFED"; // For example
NSScanner *scanner = [NSScanner scannerWithString:yourString];
NSCharacterSet *charactersToCount = #"C" // For example
NSString *charactersFromString;
if (!([scanner scanCharactersFromSet:charactersToCount intoString:&charactersFromString])) {
// No characters found
NSLog(#"No characters found");
}
NSInteger characterCount = [charactersFromString length];

UPDATE: The previous example was broken, as NSScanner should not be used like that. Here's a much more straight-forward example:
NSString* string = #"ABCCDEDRFFED";
NSCharacterSet* characters = [NSCharacterSet characterSetWithCharactersInString:#"ABC"];
NSUInteger characterCount;
NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
unichar character = [yourString characterAtIndex:i];
if ([characters characterIsMember:character]) characterCount++;
}
NSLog(#"Total characters = %d", characterCount);

Have a look at the following method in NSCharacterSet:
+ (id)characterSetWithCharactersInString:(NSString *)aString
You can create a character set with more than one character (hence the name character set), by using that class method to create your set. The parameter is a string, every character in that string will end up in the character set.

Also look up NSCountedSet. It can help you keep count of multiple instances of the same character.
For example, from the docs:
countForObject:
Returns the count associated with a given object in the receiver.
- (NSUInteger)countForObject:(id)anObject
Parameters
anObject
The object for which to return the count.
Return Value
The count associated with anObject in the receiver, which can be thought of as the number of occurrences of anObject present in the receiver.

Related

(# ゚Д゚) is a 5-letter-word. But in iOS, [#"(# ゚Д゚)" length] is 7. Why?

(# ゚Д゚) is a 5-letter-word. But in iOS, [#"(# ゚Д゚)" length] is 7.
Why?
I'm using <UITextInput> to modify the text in a UITextField or UITextView. When I make a UITextRange of 5 character length, it can just cover the (# ゚Д゚) . So, why this (# ゚Д゚) looks like a 5-character-word in UITextField and UITextView, but looks like a 7-character-word in NSString???
How can I get the correct length of a string in this case?
1) As many in the comments have already stated, Your string is made of 5 composed character sequences (or character clusters if you prefer). When broken down by unichars as NSString’s length method does you will get a 7 which is the number of unichars it takes to represent your string in memory.
2) Apparently the UITextField and UITextView are handling the strings in a unichar savvy way. Good news, so can you. See #3.
3) You can get the number of composed character sequences by using some of the NSString API which properly deals with composed character sequences. A quick example I baked up, very quickly, is a small NSString category:
#implementation NSString (ComposedCharacterSequences_helper)
-(NSUInteger)numberOfComposedCharacterSequences{
__block NSUInteger count = 0;
[self enumerateSubstringsInRange:NSMakeRange(0, self.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
NSLog(#"%#",substring); // Just for fun
count++;
}];
return count;
}
#end
Again this is quick code; but it should get you started. And if you use it like so:
NSString *string = #"(# ゚Д゚)";
NSLog(#"string length %i", string.length);
NSLog(#"composed character count %i", [string numberOfComposedCharacterSequences]);
You will see that you get the desired result.
For an in-depth explanation of the NSString API check out the WWDC 2012 Session 215 Video "Text and Linguistic Analysis"
Both ゚ and Д゚ are represented by a character sequence of two Unicode characters (even when they are visually presented as one). -[NSString length] reports the number of Unicode chars:
The number returned includes the individual characters of composed
character sequences, so you cannot use this method to determine if a
string will be visible when printed or how long it will appear.
If you want to see the byte representation:
#import <Foundation/Foundation.h>
NSString* describeUnicodeCharacters(NSString* str)
{
NSMutableString* codePoints = [NSMutableString string];
for(NSUInteger i = 0; i < [str length]; ++i){
long ch = (long)[str characterAtIndex:i];
[codePoints appendFormat:#"%0.4lX ", ch];
}
return codePoints;
}
int main(int argc, char *argv[]) {
#autoreleasepool {
NSString *s = #" ゚Д゚";
NSLog(#"%ld unicode chars. bytes: %#",
[s length], describeUnicodeCharacters(s));
}
}
The output is: 4 unicode chars. bytes: 0020 FF9F 0414 FF9F.
2) and 3): what NJones said.

ios method to insert spaces in string

In my app I download a file from amazon's s3, which does not work unless the file name has no spaces in it. For example, one of the files is "HoleByNature". I would like to display this to the user as "Hole By Nature", even though the file name will still have no spaces in it.
I was thinking of writing a method to search through the string starting at the 1st character (not the 0th) and every time I find a capital letter I create a new string with a substring until that index with a space and a substring until the rest.
So I have two questions.
If I use NSString's characterAtIndex, how do I know if that character is capital or not?
Is there a better way to do this?
Thank you!
Works for all unicode uppercase and titlecase letters
- (NSString*) spaceUppercase:(NSString*) text {
NSCharacterSet *set = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableString *result = [NSMutableString new];
for (int i = 0; i < [text length]; i++) {
unichar c = [text characterAtIndex:i];
if ([set characterIsMember:c] && i!=0){
[result appendFormat:#" %C",c];
} else {
[result appendFormat:#"%C",c];
}
}
return result;
}
I would not go to that approach because I know you can download files with spaces try this please when you construct the NSUrl object
#"my_web_site_url\sub_domain\sub_folder\My%20File.txt
this will download "My File.txt" from the URL provided. so basically you can replace all spaces in the URL with %20
reference:
http://www.w3schools.com/tags/ref_urlencode.asp
Got it working with Jano's answer but using the isupper function as suggested by Richard J. Ross III.
- (NSString*) spaceUppercase:(NSString*) text
{
NSMutableString *result = [NSMutableString new];
[result appendFormat:#"%C",[text characterAtIndex:0]];
for (int i = 1; i < [text length]; i++)
{
unichar c = [text characterAtIndex:i];
if (isupper(c))
{
[result appendFormat:#" %C",c];
}
else
{
[result appendFormat:#"%C",c];
}
}
return result;
}

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

Detecting if a character is either a letter or a number

In objective-c, how would I check if a single character was either a letter or a number? I would like to eliminate all other characters.
To eliminate non letters:
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notLetters = [[NSCharacterSet characterSetWithCharactersInString:letters] invertedSet];
NSString *newString = [[string componentsSeparatedByCharactersInSet:notLetters] componentsJoinedByString:#""];
To check one character at a time:
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if ([notLetters characterIsMember:c]) {
...
}
}
NSCharacterSet *validChars = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *invalidChars = [validChars invertedSet];
NSString *targetString = [[NSString alloc] initWithString: #"..."];
NSArray *components = [targetString componentsSeparatedByCharactersInSet:invalidChars];
NSString *resultString = [components componentsJoinedByString:#""];
Many ways to do it, here is one using character sets:
unichar ch = '5';
BOOL isLetter = [[NSCharacterSet letterCharacterSet] characterIsMember: ch];
BOOL isDigit = [[NSCharacterSet decimalDigitCharacterSet] characterIsMember: ch];
NSLog(#"'%C' is a letter: %d or a digit %d", ch, isLetter, isDigit);
You can use the C functions declared in ctype.h (included by default with Foundation). Be careful with multibyte characters though. Check the man pages.
char c = 'a';
if (isdigit(c)) {
/* ... */
} else if (isalpha(c)) {
/* ... */
}
/* or */
if (isalnum(c))
/* ... */
Checking if a character is a (arabic) number:
NSString* text = [...];
unichar character = [text characterAtIndex:0];
BOOL isNumber = (character >= '0' && character <= '9');
It would be different if you would to know other numeric characters (indian numbers, japanese numbers etc.)
Whether character is a letter depends on what you mean by letter. ASCII letters? Unicode letters?
I'm not too familiar with obj-c, but this sounds like something that can be achieved using a regex pattern.
I did some searching and found this:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
Try running a regex of "[0-9]" on each character to determine if it is a number.
Save the number to a temporary array, your array should end up with only the numbers.
I would type out the code...but as I said before, I'm not familiar with obj-c. I hope this helps though.
You can check them by comparing the ASCII value for number (0-9 ASCII ranged from 48-57) .. Also you can use NSScanner in Objective C to test for int or a char.

Finding element in array

I have the follow code:
NSArray *myArray = [NSArray arrayWithObjects: #"e", #"è", #"é",#"i","ò",nil];
NSString *string = #"simpleè";
NSMutablestring *newString;
for(i=0>;i< [string length]; i++){
if([stringa characterAtIndex:i] is in Array){
[newString appendFormat:#"%c", [string characterAtIndex:i]];
}
}
How make finding if single char of string stay in the array?
Example of result:
newString= #"ieè";
I think you want to apply rangeOfCharacterFromSet:options:range: repeatedly. You'll have to create a NSCharacterSet from the characters in your array somehow.
Added
Though it probably would be just as simple to just loop through the string with characterAtIndex and compare each char (in an inner loop) to the chars in your array (which you could extract into a unichar array or put into a single NSString to make easier to access).
Umm... if you want to check what the values are you can use NSLog
NSLog"%f", myFloat;
So you can use this to check your array... Which is what I think you are asking for, but the grammar in your question isn't very good. Please provide more details and better grammar.
You should check the length of your string and then match your string characters with the array and if found append that character in a new string.
NSString *mstr = #"asdf";
NSString *b = [ mstr characterAtIndex:0];
Hope it helps.......
You'll want to create an NSCharacterSet with the characters in the string and then ask each string in the array for its rangeOfCharacterFromSet:. If you find one where a range was actually found, then a character from the string is in the array. If not, then none of them are.
This might seem a bit roundabout, but Unicode makes looking at strings as just a series of "chars" rather unreliable, and you'll want to let your libraries do as much of the heavy lifting for you as they can.
There are better ways to do this, but this is what I think you're trying to do:
NSMutableString* result= [NSMutableString stringWithString:#""];
for( int i= 0; i < [string length]; ++i ) {
NSString* c= [NSString stringWithFormat:#"%C", [string characterAtIndex:i]];
if( [myArray containsObject:c] )
[result appendString:c];
}