Implementation of sprintf
for NSString
Extends Class: NSString
Declared In: StringSprintf.h
Discussion
This category adds a single method, sprintf:, that implements formatted strings in the manner of C's standard library function.
Methods
- -sprintf:
- (NSString*) sprintf:(NSArray*)values;
Discussion
Implements the standard C function sprintf
, using the receiver as the format string, and the elements of values as values to format. Returns a new string containing the output. sprintf: will throw an exception if too many or not enough values are supplied in the values argument.
The standard flags - -, +, (space), and # are supported, as are the width and precision modifiers (including using * to indicate that the width should be taken from the next value in the array).
sprintf: implements the following argument formats:
- s
- Interprets the value as a string, and sends it the message cStringUsingEncoding:NSUTF8Encoding to produce a character string. Note: unlike the standard C printf, width and precision modifiers for strings count the number of characters, not the number of bytes.
- @
- Similar to the use of %@ in the NSString class method stringWithFormat:. Sends the value a description message and inserts that string into the output.
- e
- E
- Prints the result of doubleValue in scientific notation. Uses the stdlib sprintf function.
- f
- Prints the result of doubleValue as a floating-point number. Uses the stdlib sprintf function.
- i
- d
- Prints the result of sending intValue to the receiver as a decimal integer.
- o
- Prints the result of sending intValue to the receiver as an unsigned octal integer.
- x
- X
- Prints the result of sending intValue to the receiver as an unsigned hexadecimal integer.
- c
- Interprets the value as an integer (using intValue) that represents a Unicode codepoint, and prints the corresponding character. This method uses F-Script's -[NSNumber unicharToString] method.
- p
- Prints the pointer address of the value as an unsigned hexadecimal integer.
The following standard formats are not supported:
-
g - shortest of exponential or floating
-
u - unsigned decimal integer
-
n - return number of written characters
Additionally, the h, l, and L modifiers (used to indicate C's short
, long
, and long double
data types) are not supported.
© Andrew Weinrich Last Updated: Wednesday, October 15, 2008