Improved code for string generation