Determine String Length Of Formatted String
Original Publication Date: 2007-May-24
Included in the Prior Art Database: 2007-May-24
The C standard library offers a wide variety of functions for outputting text to a device (such as a console, buffer, etc). These functions accept a format string that will dictate how the output will be displayed, and consists of simple text as well as special text used for special formatting of numbers, characters, strings, etc. For example, printf("The total is %d", 2+2) would result in the final formatted string "The total is 4" being displayed to the screen. In this case the format string is "The total is %d", which contains special text "%d" for outputting a number. This invention is an algorithm that will calculate the length of the final formatted string that would result from a call to a standard C library such as printf. In the example above, our algorithm would calculate a length of 14 (the length of the string "The total is 4"). If we know the size of the resulting string, we can dynamically allocate the exact amount of memory needed to store that string. This prevents over allocation of memory, but more importantly it prevents under allocation which causes unexpected failures in programs. A different solution, would be to print the final string to a file, then read the file and calculate the number of characters. The drawback to this is the use of file I/O which can potentially make it very slow for large strings.