snprintf method

String snprintf(
  1. int n,
  2. String format, [
  3. List args = const []
])

Writes formatted output to a String, truncated to at most n-1 characters.

Mirrors C's snprintf size-limit convention (reserves one byte for \0). Returns the (possibly truncated) String rather than a character count.

Deviation from C: returns a String directly instead of writing to a buffer.

Example:

stdc.snprintf(6, "Hello, %s!", ["World"]); // "Hello"
stdc.snprintf(20, "%08.3f", [3.14]);        // "0003.140"

Implementation

String snprintf(int n, String format, [List<dynamic> args = const []]) {
  if (n <= 0) return '';
  final full = sprintf(format, args);
  return full.length >= n ? full.substring(0, n - 1) : full;
}