I want to get the ranges of members within an NSString
built with +[NSString stringWithFormat:]
. What is the best way to parse the objective-c format string? I can't just use a C format string parser because of %@
. I also need to make sure it supports format orderings: %1$d
, %2$@
, etc.
For example, with the string built with [NSString stringWithFormat:@"foo %2$@ bar %1$@", @"Heath", @"Borders"]
, I would ideally like the following NSArray
: @[NSMakeRange(15, 5), NSMakeRange(4, 6)]
. The first array object corresponds to the first data element in the format string, the second array object to the second data element, etc.
In this case, the API would look something like + (NSString *) stringWithFormatRanges:(NSArray **)outFormatRanges withFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
It would return an NSString
just like +[NSString stringWithFormat:]
, but it would also return an NSArray
with NSRange
s of each format data element.
-- EDIT --
Given that this question is 3 years old, I'd be happy with a C-only implementation at this point.
We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of “%zu”. In “%zu” format, z is a length modifier and u stand for unsigned type.
The printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages.
We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).
I looked into this a few years ago. If I understand your question, there's no easy way to get the AST from a format string for either C or Cocoa format strings.
I wrote NSXMLElement+elementWithXMLFormat which allowed unescaped insertion of NSXMLElements into a format string with a special %%%@
format code, which required extending Cocoa's format. My technique may be helpful to you:
https://github.com/rentzsch/nsxmlelement-elementwithxmlformat/blob/937b54b2a830a8fbbd72d6bc5e48bafd495ddcbd/NSXMLElement%2BelementWithXMLFormat.m#L41
I extract and NUL-delimit just the format codes, run it through traditionally and then reassemble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With