string

A `printf` format reference page (cheat sheet)

Summary: This page is a printf formatting cheat sheet. I originally created this cheat sheet for my own purposes, and then thought I would share it here.

A great thing about the printf formatting syntax is that the format specifiers you can use are very similar — if not identical — between different languages, including C, C++, Java, Perl, PHP, Ruby, Scala, and others. This means that your printf knowledge is reusable, which is a good thing.

A Dart string capitalize function

I was surprised to learn that Dart doesn’t have a string capitalize method, so if you ever need a capitalize method/function, here’s a start towards a solution:

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

That function will work with Dart strings like these:

Dart: How to remove leading spaces in a multiline string (using splitMapJoin)

As far as I know, there’s no built-in way to remove spaces from a multiline string in Dart, but you can write your own function to do this. For example, I just dug into the splitMapJoin method of the Dart String class, and wrote a stripMargin function like this:

String stripMargin(String s) {
    return s.splitMapJoin(
        RegExp(r'^', multiLine: true),
        onMatch: (_) => '\n',
        onNonMatch: (n) => n.trim(),
    );
}
A Flutter function to convert a TimeOfDay to a String (formatted) alvin September 18, 2019 - 6:44pm

If you ever need a Dart/Flutter method to format a TimeOfDay variable — i.e., convert a TimeOfDay to a String — I can confirm that this method works:

String formatTimeOfDay(TimeOfDay tod) {
    final now = new DateTime.now();
    final dt = DateTime(now.year, now.month, now.day, tod.hour, tod.minute);
    final format = DateFormat.jm();  //"6:00 AM"
    return format.format(dt);
}

Unix/Linux: Find all files that contain multiple strings/patterns

When using Unix or Linux, if you ever need to find all files that contain multiple strings/patterns, — such as finding all Scala files that contain 'try', 'catch', and 'finally' — this find/awk command seems to do the trick:

find . -type f -name *scala -exec awk 'BEGIN {RS=""; FS="\n"} /try/ && /catch/ && /finally/ {print FILENAME}' {} \;

As shown in the image below, all of the matching filenames are printed out. As Monk says, you’ll thank me later. :)

(I should mention that I got part of the solution from this gnu.org page.)

Update: My File Find utility

For a potentially better solution, see my File Find utility, which lets you search for multiple regex patterns in files.

Scala/Java: How to convert a stack trace to a string for printing with a logger

As a quick note, I just got a little bit better about logging stack traces when writing Java or Scala code. In Scala I used to get the text from a stack trace and then log it like this:

// this works, but it's not too useful/readable
logger.error(exception.getStackTrace.mkString("\n"))

In that code, getStackTrace returns a sequence, which I convert to a String before printing it.

An example of Scala’s `f` string interpolator

With Scala it’s common to embed variables in strings like this with the s string interpolator:

val name = "Fred"
println(s"My name is $name.")

That’s cool, but when you need to format your string, Scala gives you an even more powerful tool: the f string interpolator. Here’s an example of how I just did this in my LittleLogger logging library:

How to left-justify a multiline Scala string

If you ever need to left-justify a multiline Scala string, the solution is to use the stripMargin method, as shown in this example:

def getWordFormatted(s: String): String = {
    s"""
      |
      |Word of the Day
      |---------------
      |Word: $s
    """.stripMargin
}

The | character has a special meaning when used in conjunction with stripMargin, so that method results in a string like this being output: