I am currently using this code to put some text on the screen
userOutput.text=#"";
I want to be able to display an int variable in the string, like you do with printf in C with the %d placeholders. How do I do this with an NSString
int whatever = 42;
userOutput.text = [NSString stringWithFormat:#"%d", whatever];
use NSString's +stringWithFormat: method:
userOutput.text= [NSString stringWithFormat: #"%d", 100];
It uses exactly the same format specifiers as printf function in c.
Related
I have a string which already contains a formatter %#.
NSString *str = #"This is an %#";
I need to parse that string and to replace %# with 'example'. If I use
[NSString stringWithFormat:#"%#", str];
I get the following output:
This is an %#
I want output like:
This is an example
NSString *str = #"This is an %#";
str = [str stringByReplacingOccurrencesOfString:#"%#" withString:#"example"];
I would recommand to use the formatted string as "format"
NSString *str = #"This is an %#";
str = [NSString stringWithFormat:str, #"example"];
is working with every type. A better solution than replacing, because you can use unspecified replacings
is very usefull if you use localized.strings with x values you want to add ;)
How can I get the functionality of sprintf in Objective-C? The function is of course part of stdio in C, so I could certainly invoke it, but since I'm using Foundation, I need it to work with NSStrings as well.
EDIT
I apologize for my inarticulateness, but I'm actually hoping for something more like the PHP sprintf function that returns a string. (This was perhaps slightly evident before Josh Caswell's very efficient edit of my question.) It would be like NSLog but instead of writing to console would give a string (or pointer) as a return value.
The closest function that does the same thing in Cocoa is NSString's stringWithFormat.
Using sprintf:
char buf[100];
sprintf(buf, "Line %d of %d", currentLine, totalLines);
Using stringWithFormat:
NSString res = [NSString stringWithFormat:#"Line %d of %d", currentLine, totalLines];
Note that stringWithFormat: supports printing of Cocoa objects with %# format specifier.
One option:
NSString *OCSprintf(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);
NSString *OCSprintf(NSString *format, ...)
{
va_list args;
va_start(args, format);
NSString *result = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
va_end(args);
return result;
}
This just wraps stringWithFormat: (more precisely, one of its cousins) as a function as you requested. The NS_FORMAT_FUNCTION(1,2) ensures you still get format string checking.
NSString * myString = [NSString stringWithFormat:#"...", params…];
const char * myStrPtr = [myString UTF8String];
Is there any simple way how to initialize String in Objective-C with int such as in Java:
String myStr = 42 + "";
or I have to do
[NSString stringWithFormat:#"%d", 42];
everytime?
You could also use the NSNumber class for that:
NSNumber *number = [[NSNumber alloc] initWithInteger: val];
NSString *string = [number stringValue];
Perhaps not shorter, but it could be eventually faster.
Also you could create as said a helper method, than you wouldn't have to use more code than with the stringWithFormat: method.
Yes you have to do
[NSString stringWithFormat:#"%d", 42];
for Integer to string conversion.
Using a constant, like 42 in your example, you can write
NSString *myString = #"42";
Using a variable or expression, you can write
[NSString stringWithFormat:#"%d", myValue];
Do you know how can i convert float value to nsstring value because with my code, there is an error.
My Code :
- (float)percent:(float)a :(float)b{
return a / b * 100;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// ....
float tx_nb_demande_portabilite = [self percent: [(NSNumber*) [stat nb_demande_portabilite] floatValue] :[(NSNumber*) [stat nb_users] floatValue]];
NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
//....
}
The error :
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
Thank you for your help.
You need to use %f format specifier for float, not %#.
NSString *str = [NSString stringWithFormat:#"%f", myFloat];
To use specific number of digits after decimal use %.nf where n is number of digits after decimal point.
// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:#"%.3f", myFloat];
Obj-C uses C printf style formatting. Please check printf man page for all other possible formatting.
one more option:
NSString * str = [NSNumber numberWithFloat:value].stringValue;
#"%f" sounds like more appropriate format string for float.
[NSString stringWithFormat:#"%f", tx_nb_demande_portabilite];
A modern (and less verbose) approach would be:
NSString *str = #(myFloat).description;
How would I use a combination of text and variables in a NSString?
I know that in an NSLog, it looks like this:
int number = 5;
NSLog(#"My favorite number is %i", number);
How would I go about doing something like that in an NSString or even a char variable?
That is fairly simple:
NSString *string = [NSString stringWithFormat:#"My favorite number is %i", number];
its basically the same as nslog.
NSString * str = [NSString stringWithFormat:#"My favorite number is %i", number];
if you just want to read about format specifiers, see: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
use all the power of old beloved printf formatting.
for objects "%#" will call the description method, so be smart to write this method for every custom class:
-(NSString*)description;
{
NSString* result = [NSString stringWithFormat(#"%#" .......
}
for example:
-(NSString *)description;
{
return [NSString stringWithFormat:#"is: %# %# %# ; at: %f %f",
name, address, img_name,
coord.latitude, coord.longitude];
}