Algorithm to convert 1 to "One" and so on in objective-c [duplicate] - objective-c

This question already has answers here:
How to convert numbers into text?
(8 answers)
Closed 7 years ago.
I'm looking for an algorithm or function to convert integer number 0,1,2 to Zero,One,Two respectively. How can we do this in Objective-C ?

Apple has a lot of handy formatting functionality built in for many data types. Called a "formatter," they can convert objects to/from string representations.
For your case, you will be using NSNumberFormatter, but if you have an integer you need to convert it to an NSNumber first. See below example.
NSInteger anInt = 11242043;
NSString *wordNumber;
//convert to words
NSNumber *numberValue = [NSNumber numberWithInt:anInt]; //needs to be NSNumber!
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
wordNumber = [numberFormatter stringFromNumber:numberValue];
NSLog(#"Answer: %#", wordNumber);
// Answer: eleven million two hundred forty-two thousand forty-three

This is my code for 0 to 100 (You can update as per your requirement). WORKING PERFECTLY !!
-(NSDictionary *)algorithm
{
NSArray *myArray = #[#"Zero",#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",#"Ten",#"Eleven",#"Twelve",#"Thirteen",#"Fourteen",#"Fifteen",#"Sixteen",#"Sevteen",#"Eighteen",#"Nineteen"];
NSArray *tensArray = #[#"Twenty",#"Thirty",#"Fourty",#"Fifty",#"Sixty"
,#"Seventy",#"Eighty",#"Ninety",#"One Hundred"];
NSMutableDictionary *numberStringDictionary = [[NSMutableDictionary alloc] init];
NSMutableArray *numberStringsArray = [[NSMutableArray alloc] init];
for(int i=0;i<=100;i++)
{
if(i<20)
{
[numberStringDictionary setObject:myArray[i] forKey:[NSString stringWithFormat:#"%d",i]];
[numberStringsArray addObject:myArray[i]];
NSLog(#"\n%#",myArray[i]);
}
else if(i%10==0)
{
[numberStringDictionary setObject:tensArray[i/10-2] forKey:[NSString stringWithFormat:#"%d",i]];
[numberStringsArray addObject:tensArray[i/10-2]];
NSLog(#"\n%#",tensArray[i/10-2]);
}
else
{
[numberStringDictionary setObject:[NSString stringWithFormat:#"%# %#",tensArray[i/10-2],myArray[i%10]] forKey:[NSString stringWithFormat:#"%d",i]];
[numberStringsArray addObject:[NSString stringWithFormat:#"%# %#",tensArray[i/10-2],myArray[i%10]]];
NSLog(#"%#",[NSString stringWithFormat:#"%# %#",tensArray[i/10-2],myArray[i%10]]);
}
}
return numberStringDictionary;
}

Related

Using NSNumber to sort numerous integers

Ive been doing alot of research and can't quite grasp resolving this issue. In my application I have several text fields that save integer values in the form of int variables (at least 15 int variables). My main goal is to sort out high to low numbers that were saved from the text fields.
Now would I use the following code to convert each seperate integer variable into a new NSNumber, than use a sort function to sort out the new NSNumbers from high to low?
NSNumber *newNumber = [NSNumber numberWithInt: my_int_variable];
I just feel as if this is a redundant way of sorting 12 integer variables and there is a easier way. Thank you for the help
Going from individual text fields to strings to ints to NSNumbers to an array to a sorted array is long, clunky trip. But a worthwhile trip nevertheless.
// assume these
UITextField *field0;
UITextField *field1;
UITextField *field2;
// make an array for the input and the result
NSArray *textFields = #[field0, field1, field2];
NSMutableArray *numbers = [#[] mutableCopy];
// prepare a number formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
// lots of choices here. see https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/index.html
for (UITextField *textField in textFields) {
NSString *text = textField.text;
NSNumber *number = [formatter numberFromString:text];
[numbers addObject:number];
}
// sort...a few choices here, too. taking the simplest:
[numbers sortUsingSelector:#selector(compare:)];
NSLog(#"ta da: %#", numbers);
Or did you want to sort the text fields based on their contents? Doable too:
NSMutableArray *textFields = [#[field0, field1, field2] mutableCopy];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
[textFields sortedUsingComparator: ^(id objA, id objB) {
NSString *textA = ((UITextField *)objA).text;
NSString *textB = ((UITextField *)objB).text;
NSNumber *numberA = [formatter numberFromString:textA];
NSNumber *numberB = [formatter numberFromString:textB];
return [numberA compare:numberB];
}];
NSLog(#"text fields in order of their contents: %#", textFields);

Encoding issue: An NSString into a key of an NSDictionary

So I'm taking a data file and encoding it into a string:
///////////////////////////////
// Get the string
NSString* dataString = [[NSString alloc] initWithData:data
encoding:encoding];
NSLog(#"dataString = %#",dataString);
The file was a list of French words and they NSLog fine, showing appropriate accents (just one example):
abandonnèrent
Now, in the very next part of the code I take this NSString of the file contents and convert it to a dictionary where the words are the keys and the objects are two additional dictionaries:
///////////////////////////////
// Now parse the file (string)
NSMutableDictionary *mutableWordlist = [[NSMutableDictionary alloc] init];
int i = 0;
for (NSString *line in [dataString componentsSeparatedByString:#"\n"]) {
NSArray *words = [line componentsSeparatedByString:#"\t"];
NSNumber *count = [NSNumber numberWithInt:(i+1)];
NSArray *keyArray;
NSArray *objectArray;
if ([words count] < 2) { // No native word
keyArray = [[NSArray alloc] initWithObjects:#"frequency", nil];
objectArray = [[NSArray alloc] initWithObjects:count, nil];
}
else {
keyArray = [[NSArray alloc] initWithObjects:#"frequency", #"native", nil];
objectArray = [[NSArray alloc] initWithObjects:count, [words[1] lowercaseString], nil];
}
NSDictionary *detailsDict = [[NSDictionary alloc] initWithObjects:objectArray forKeys:keyArray];
[mutableWordlist setObject:detailsDict forKey:[words[0] lowercaseString]];
i++;
}
self.wordlist = mutableWordlist;
NSLog(#"self.wordlist = %#", self.wordlist);
But here the keys have encoding issues and log as so if they have an accent:
"abandonn\U00e8rent
" = {
frequency = 24220;
};
What is happening?
Nothing (wrong) is happening.
When you NSLog an NSString it is being output as Unicode text. However when you NSLog the NSDictionary they keys are being output with unicode escape sequences, \U00e8 is the escape code you can use in a string if you cannot type an è - say because your source file is in ASCII.
So the difference is only in how the string is being printed, the string is not different.
HTH

Convert a string to a positive or negative number

I am new to ObjC. I've spent years working in Applescript and I've decided to move up. I am a hobbiest programmer.
I have the following code:
+(NSArray *) initArrayWithFileContents:(NSString *) theFilePath
{
NSString *theContents = [(self) loadFile:theFilePath]; // returns the contents of a text file
NSArray *theParagraphs = [(self) getParagraphs:theContents]; // returns the contents as an array of paragraphs
NSMutableArray *teamData = [[NSMutableArray alloc] init]; // array of team data
NSMutableArray *leagueData = [[NSMutableArray alloc] init]; // array of arrays
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
for (NSString *currentParagraph in theParagraphs)
{
NSArray *currentTeam = [(self) getcolumnarData:currentParagraph];
for (NSString *currentItem in currentTeam)
{
NSNumber *currentStat = [numberStyle numberFromString:currentItem];
if (currentStat != Nil) {
[teamData addObject:currentStat];
} else {
[teamData addObject:currentItem];
}
}
[leagueData addObject:teamData];
[teamData removeAllObjects];
}
return leagueData;
}
This works fine for strings and for negative numbers, but a number preceded by a "+" sign is returned as a string. I figure I need to use a different number formatter style but I don't know what to use.
Thanks in advance,
Brad
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[numberStyle setPositiveFormat:#"'+'#"] ;
or
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[numberStyle setPositivePrefix:#"+"] ;
You could remove the + sign if one exists:
if ([currentItem hasPrefix:#"+"])
{
currentItem = [currentItem substringWithRange:NSMakeRange(1, [currentItem length] -1)];
}
Probably a better way, but this would work.
What ended up working for me was to create 2 NSNumberFormatters; 1 for decimals and 1 for decimals using the setPositiveFormat: method as described above. If the first formatter doesn't work, it'll flow on to the next formatter using the positive format.

Sort NSMutableArray with strings that contain numbers?

I have a NSMutableArray and it has the users high scores saved into it. I want to arrange the items numerically (the numbers are stored in NSStrings.)Example:4,2,7,8To2,4,7,8What is the simplest way to do this if the data is stored in NSStrings?
This code will do it:
//creating mutable array
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:#"4", #"2", #"7", #"8", nil];
//sorting
[myArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
return [str1 compare:str2 options:(NSNumericSearch)];
}];
//logging
NSLog(#"%#", myArray);
It uses blocks, make sure your target OS supports that (It's 4.0 for iOS and 10.6 for OSX).
This code works. I tried it:
NSMutableArray *unsortedHighScores = [[NSMutableArray alloc] initWithObjects:#"4", #"2", #"7", #"8", nil];
NSMutableArray *intermediaryArray = [[NSMutableArray alloc] init];
for(NSString *score in unsortedHighScores){
NSNumber *scoreInt = [NSNumber numberWithInteger:[score integerValue]];
[intermediaryArray addObject:scoreInt];
}
NSArray *sortedHighScores = [intermediaryArray sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"%#", sortedHighScores);
The output is this:
2
4
7
8
If you have any questions about the code, just ask in the comments. Hope this helps!
The NSMutableArray method sortUsingSelector: should do it:
[scoreArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)]
should do it.
If the array is of nsdictionaries conaining numeric value for key number
isKeyAscending = isKeyAscending ? NO : YES;
[yourArray sortUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSString *str1 = [obj1 objectForKey:#"number"];
NSString *str2 = [obj2 objectForKey:#"number"];
if(isKeyAscending) { //ascending order
return [str1 compare:str2 options:(NSNumericSearch)];
} else { //descending order
return [str2 compare:str1 options:(NSNumericSearch)];
}
}];
//yourArray is now sorted
The answer from Darshit Shah make it smootly
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:#"rank" ascending:YES selector:#selector(localizedStandardCompare:)];

how to convert integer to string? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to convert from int to string in objective c: example code…
How to convert integer to string in Objective C?
NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];
Update for new Objective-C syntax:
NSArray *myArray = #[#1, #2, #3];
Those two declarations are identical from the compiler's perspective.
if you're just wanting to use an integer in a string for putting into a textbox or something:
int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:#"%i", myInteger];
If you really want to use String:
NSString *number = [[NSString alloc] initWithFormat:#"%d", 123];
But I would recommend using NSNumber:
NSNumber *number = [[NSNumber alloc] initWithInt:123];
Then just add it to the array.
[array addObject:number];
Don't forget to release it after that, since you created it above.
[number release];
NSString* myNewString = [NSString stringWithFormat:#"%d", myInt];