I have a piece of code that is supposed to generate output like
3 files uploaded
1 file uploaded
129 files uploaded
and the point of concern is how to handle the fact that either file or files is printed out depending on whether the number of files is greater than 1. The best I could come up with is
output = numFiles.toString() + " file" + (numFiles > 0 ? "s" : "") + " uploaded\n";
but the problem is that if numFiles is 0 the expression is adding an empty string, which is a useless operation. I want to cut down on that useless operation. I realize I could do that by
output = numFiles.toString() + " file";
if (numFiles > 0) output += "s";
output = " uploaded\n";
but then my code is 3 lines long and it's probably still inefficient to perform string addition when the second string is of length 1 like "s" is. Is there a way to push back a single character on to a string? How else can I optimize this procedure?
Aucun commentaire:
Enregistrer un commentaire