patternjavaMinor
Java String iterations
Viewed 0 times
stringiterationsjava
Problem
I am working with some Java code. Basically I have a wrapper class that holds a string and implements some of the many useful python string methods in Java. My goal here is to implement the Python method
In the above case,
The other option would be
In this case,
I am interested in perspectives on which of these alternatives is most efficient as well as any other optimizations you could provide for this method, which is meant to pad a string with
.ljust and my hope is to be as efficient as possible. Currently, I am using a while loop which I imagine is terrible inefficient especially because it includes a +=. What's more, I am not sure which of the following alternatives is more efficientString news = "";
news = this.toString();
int length = news.length();
while (length < size) {
news += " ";
length++;
}
return new PythonString(news);In the above case,
news.length() is only called once, but now there is an extra int and a new instruction length++.The other option would be
String news = "";
news = this.toString();
while (news.length() < size) {
news += " ";
}
return new PythonString(news);In this case,
news.length() is called every time. I am interested in perspectives on which of these alternatives is most efficient as well as any other optimizations you could provide for this method, which is meant to pad a string with
size spaces to the right so that all following characters line up at the same column.Solution
The String class can do this already, see answer here: https://stackoverflow.com/a/391978/4217399. You can always look at the source of the String class to check how it's done, should be fairly optimized there, as it's a part of the JDK. It's actually offloaded to the java.util.Formatter class.
Context
StackExchange Code Review Q#114959, answer score: 5
Revisions (0)
No revisions yet.