Search code examples
string-formattingchapel

How do I format strings output in Chapel?


When I'm printing numbers with Chapel's Formatted I/O I can set the length of numbers with something like

writeln("my number is %{#.###}", 3.14159)

I want to something similar with strings, but I don't see an example on the page. Basically, I'd like the string to line up in nice columns.


Solution

  • Your example is confusing writeln with writef. To use formatted IO in writeln, you'll need to invoke the .format() method. Here is an example that demonstrates the string format specifier (%s) and the generic format specifier (%t). These are listed on the page you've linked in the question.

    config var someString = 'ben';
    
    // String format specifier
    writeln('%s is great'.format(someString));
    writef('%s is awesome\n', someString);
    
    
    // Generic format specifier invokes the readThis / writeThis of the object
    writeln('%t is awesome x%t'.format(someString, 2));
    

    Output:

    ben is great
    ben is awesome
    "ben" is awesome x2
    

    Note that string objects include quotes in their writeThis method, so you get quotes when using a string with the generic format specifier.