So, I have this code snippet.
while (!Character.isWhitespace(this.source.charAt(this.currentCharIndex))) {
char c = this.source.charAt(this.currentCharIndex);
// ...
}
What it does is just basically loops through a string until it hits a white space character.
However, I find the code a bit messy. How can I improve it?
I can try this code snippet instead.
char c = this.source.charAt(this.currentCharIndex);
while (!Character.isWhitespace(c)) {
c = this.source.charAt(this.currentCharIndex);
}
It looks cleaner but this.source.charAt(this.currentCharIndex)
seems redundant (the same as the previous snippet) so I need your opinion on how you would tackle this problem.
Thanks! :D
Top comments (8)
maybe...
or
but I know nothing of what happen next tho... I assume currentCharIndex will be increment somewhere in the loop...
(I don't use Java, but) I'd probably use the Java Streams API.
Using
Optional
makes it obvious you have to handle when whitespace is not found.Note: not guaranteed to compile.
Well, you give very little context about your intentions.
If it is safe to assume that currentCharIndex is within the correct bounds, you might get rid of the assignment outside of the loop by using do { } while.
Or, you get rid of the imperative style by using Streams (you get an IntStream from a String using the chars() method in Java 8).
Interesting. I'm actually creating a tokenizer for a programming language we came up as part of our course curriculum.
Use a
find_first
function, writing your own if it doesn't exist.If you simply want the first instance of a certain character, and the context is not more complex, and it doesn't require hyper-optimisation, then just go with source.indexOf(" ")
char c = this.source.charAt(this.currentCharIndex);
while (!Character.isWhitespace(c)) {
char d = c;
}
}
Gave up on markdown..
It's Java (though I initially thought there was enough clues that it was Java, my bad). The code snippet is actually inside a class.