During a stint programming with Qt, I became quite fond of using QString’s arg(), which allows you embed arguments into a template string. QString copies the template, replacing markers with the arugments. It seems obvious, but it is dead useful, especially when it comes to translating software. For example, straight from theĀ documentation:

     QString i;           // current file's number
     QString total;       // number of files to process
     QString fileName;    // current file's name

     QString status = QString("Processing file %1 of %2: %3")
                     .arg(i).arg(total).arg(fileName);

See, dead useful, right? I’ve recently been programming with my first love (Java, obviously) and have run against a problem that made Qt/C++ once seem so much more attractive. Althogh String itself is pretty barebones, it turns out there’s help; allow me to introduceĀ MessageFormat. I’m not sure how I never came to know this class, but it’s satisfied me for want. It has a slightly more verbose format, but also has some swell extras. For example, how about agreeing with the number of a noun?

     MessageFormat.format("You did not guess {0} {0,choice,0#words
                          |1#word|1<words}.\n", allWords.size());

Color me smitten. Harmony between Java and me is, for the moment, restored.

Leave a Reply