NSString stringWithFormat question - iphone

I am trying to build a small table using NSString. I cannot seem to format the strings properly.
Here is what I have
[NSString stringWithFormat:#"%8#: %.6f",e,v]
where e is an NSString from somewhere else, and v is a float.
What I want is output something like this:
Grapes: 20.3
Pomegranates: 2.5
Oranges: 15.1
What I get is
Grapes:20.3
Pomegranates:2.5
Oranges:15.1
How can I fix my format to do something like this?

you could try using - stringByPaddingToLength:withString:startingAtIndex:

NSDictionary* fruits = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:20.3], #"Grapes",
[NSNumber numberWithFloat:2.5], #"Pomegranates",
[NSNumber numberWithFloat:15.1], #"Oranges",
nil];
NSUInteger longestNameLength = 0;
for (NSString* key in [fruits allKeys])
{
NSUInteger keyLength = [key length];
if (keyLength > longestNameLength)
{
longestNameLength = keyLength;
}
}
for (NSString* key in [fruits allKeys])
{
NSUInteger keyLength = [key length];
NSNumber* object = [fruits objectForKey:key];
NSUInteger padding = longestNameLength - keyLength + 1;
NSLog(#"%#", [NSString stringWithFormat:#"%#:%*s%5.2f", key, padding, " ", [object floatValue]]);
}
Output:
Oranges: 15.10
Pomegranates: 2.50
Grapes: 20.30

The NSNumberFormatter class is the way to go!
Example:
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setPaddingCharacter:#"0"];
[numFormatter setFormatWidth:2];
NSString *paddedString = [numFormatter stringFromNumber:[NSNumber numberWithInteger:integer]];
[numFormatter release];

I think you want something like
[NSString stringWithFormat:#"%-9# %6.1f",[e stringByAppendingString:#":"],v]
since you want padding in front of the float to make it fit the column, though if the NSString is longer than 8, it will break the columns.
%-8f left-aligns the string in a 9-character-wide column (9-wide since the : is appended to the string beforehand, which is done so the : is at the end of the string, not after padding spaces); %6.1f right-aligns the float in a 6-char field with 1 decimal place.
edit: also, if you're viewing the output as if it were HTML (through some sort of web view, for instance), that may be reducing any instances of more than one space to a single space.

Related

How to convert currency from string format to number format?

I need to convert currency from string format to number format.
For example my string variable value is #"10 lakh". The string value for this converted into number format would be 1000000. How can one make this type of conversion?
(Converting 10 lakh to 1000000, this is the issue)
Try
- (NSNumber *)multiplierForKey:(NSString *)key
{
NSDictionary *dict = #{#"thousand":#1000, #"lakh":#100000, #"million":#1000000, #"crore":#100000000};
NSNumber *value = dict[[key lowercaseString]];
return value?value:#1;
}
- (void)findMultiplier{
NSString *string = #"10 lakh";
NSArray *components = [string componentsSeparatedByString:#" "];
if ([components count]==2) {
NSNumber *value = components[0];
NSString *key = components[1];
NSNumber *multiplier = [self multiplierForKey:key];
NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithDecimal:[value decimalValue]];
NSDecimalNumber *multiplierValue = [NSDecimalNumber decimalNumberWithDecimal:[multiplier decimalValue]];
NSDecimalNumber *finalValue = [decimalValue decimalNumberByMultiplyingBy:multiplierValue];
NSLog(#"Value : %#",finalValue);
}
}
You can make switch cases according to your denominations. By choosing particular switch case you can choose the desired value. I don't think there is predefined method to accomplish this.
hope this helps.

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

How to create a comma-separated string?

I want to create a comma-separated string like this.
NSString *list = #"iPhone,iPad,iPod";
I tried like this,
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
But the issue is I'm getting a string like this
#"iPhone,iPad,iPod," Note that there is an extra comma "," at the end of the string. How can I avoid that extra comma?
Can you please give me a hint. Highly appreciated
Thanks in advance
To join an array of strings into a single string by a separator (character which would be a string), you could use this method of NSArray class:
NSArray* array = #[#"iPhone", #"iPad", #"iPod"];
NSString* query = [array componentsJoinedByString:#","];
By using this method, you won't need to drop the last extra comma (or whatever) because it won't add it to the final string.
There's a couple of routes you can take.
If the number of items is always the same, and known before hand (which I guess isn't the case, but I mention it for completeness's sake), just make the whole string at once:
[NSString stringWithFormat:#"%#,%#,%#", [[arrItems objectAtIndex:0] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:1] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:2] objectForKey:#"ItemList"]]
Knowing that the unwanted comma will always be the last character in the string, you can make removing it the last step in construction:
} // End of loop
[strItemList removeCharactersInRange:(NSRange){[strItemList length] - 1, 1}];
Or you can change your thinking a little and do the loop like this:
NSString * comma = #"";
for( i = 0; i < [arrItems count]; i++ ){
[strItemList appendString:[NSString stringWithFormat:#"%#%#", comma, [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
comma = #",";
}
Notice that comma comes before the other item. Setting that string inside the loop means that nothing will be added on the first item, but a comma character will be for every other item.
After Completion of loop add below stmt
strItemList = [strItemList substringToIndex:[strItemList length]-1]
check the value of array count if array count is last then add without comma else add with comma. try this out i am not sure to much about.
if([arrItems objectAtIndex:i] == arrItems.count){
[strItemList appendString:[NSString stringWithFormat:#"%#", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
else {
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
Assuming that arrItems is an NSArray with elements #"iPhone", #"iPad", and #"iPod", you can do this:
NSArray *list = [arrItems componentsJoinedByString:#","]
NSArray with elements #"iPhone", #"iPad", and #"iPod"
NSString *str=[[arrItems objectAtIndex:0]objectForKey:#"ItemList"]]
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:1]objectForKey:#"ItemList"]]];
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:2]objectForKey:#"ItemList"]]];
NsLog(#"%#",str);
// Assuming...
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPhone", #"iPodTouch", nil] forKey:#"ItemList"];
NSDictionary *dictionary2 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPad", #"iPad2", #"Apple TV", nil] forKey:#"ItemList"];
NSDictionary *dictionary3 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iMac", #"MacBook Pro", #"Mac Pro", nil] forKey:#"ItemList"];
NSArray *arrItems = [NSArray arrayWithObjects:dictionary1, dictionary2, dictionary3, nil];
// create string list
NSString *strItemList = [[arrItems valueForKeyPath:#"#unionOfArrays.ItemList"] componentsJoinedByString:#", "];
NSLog(#"All Items List: %#", strItemList);
Output:
All Items List: iPhone, iPodTouch, iPad, iPad2, Apple TV, iMac, MacBook Pro, Mac Pro
This method will return you the nsmutablestring with comma separated values from an array
-(NSMutableString *)strMutableFromArray:(NSMutableArray *)arr withSeperater:(NSString *)saperator
{
NSMutableString *strResult = [NSMutableString string];
for (int j=0; j<[arr count]; j++)
{
NSString *strBar = [arr objectAtIndex:j];
[strResult appendString:[NSString stringWithFormat:#"%#",strBar]];
if (j != [arr count]-1)
{
[strResult appendString:[NSString stringWithFormat:#"%#",seperator]];
}
}
return strResult;
}

NSRegularExpression to extract text

All,
I have a dictionary with two keys and values. I need to extract bits and pieces from them and place them into seperate strings.
{
IP = "192.168.17.1";
desc = "VUWI-VUWI-ABC_Dry_Cleaning-R12-01";
}
That is what the dictionary looks like when I call description.
I want the new output to be like this:
NSString *IP = #"192.168.17.1";
NSString *desc = #"ABC Dry Cleaning"; //note: I need to get rid of the underscores
NSString *type = #"R";
NSString *num = #"12";
NSString *ident = #"01";
How would I achieve this?
I've read through the Apple developer docs on NSRegularExpression but I find it hard to understand. I'm sure once I get some help once here I can figure it out in the future, I just need to get started.
Thanks in advance.
Okay, so first, you have to get the object associated with each key:
NSString *ip = [dic objectForKey:#"IP"]; //Btw, you shouldn't start a variable's name with a capital letter.
NSString *tempDesc = [dic objectForKey:#"desc"];
Then, what I would do is split the string in tempDesc, based on the character -.
NSArray *tmpArray = [tempDesc componentsSeparatedByString:#"-"];
Then you just have to get the strings or substrings you're interested in, and reformat them as needed:
NSString *desc = [[tmpArray objectAtIndex:2] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *type = [[tmpArray objectAtIndex:3] substringToIndex:1];
NSString *num = [[tmpArray objectAtIndex:3] substringFromIndex:1];
NSString *ident = [tmpArray objectAtIndex:4];
As you can see, this works perfectly without using NSRegularExpression.

Convert char to int to NSString

I am writing some code to allow users to answer multiple choice questions. So I have an NSArray of values [#"value1", #"value2", ..]
I want to display them as:
A) value1
B) value2
The code I have is
for(int i = i; i < [values count]; i = i+1) {
NSString *displayValue = [[NSString alloc] initWithString:<NEED HELP HERE>];
displayValue = [displayValue stringByAppendingString:#") "];
displayValue = [displayValue stringByAppendingString:[values objectAtIndex:i];
}
The question I have is if there is where I have put , how could I convert i to the right ASCII character (A, B, C, etc) and initialize the string with that value
NSString *displayValue = [NSString stringWithFormat:#"%c",'A'-1+i];
and to get the whole string at once, use:
NSString *displayValue = [NSString stringWithFormat:#"%c) %#",'A'-1+i,
[values objectAtIndex:i]];
(ps. if you alloc an object, you must also release or autorelease, or you will "leak" memory)
Look at NSString:initWithFormat method, along with the String Programming Guide.