How can I improve this while loop code snippet?

twitter logo github logo ・1 min read

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

twitter logo DISCUSS (9)
markdown guide


        char c;
        while (!Character.isWhitespace(c=source.charAt(currentCharIndex++))) {
            //do code magic here...


        char c;
        while (!Character.isWhitespace(c=source.charAt(currentCharIndex))) {
            //more code magic happen after this...

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.

Optional<int> whitespaceIndex =
    IntStream.range(0, this.source.length())
        .filter(i -> Character.isWhiteSpace(this.source.charAt(i)))
Optional<char> whitespaceChar = whitespaceIndex.map(i -> this.source.charAt(i));

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.


The era when there was one single programming language is over. You might start with telling us what language is it.


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.


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..

Classic DEV Post from Jun 14 '19

Stopping Bad Habits Before They Stop You

Stop habits before they derail your life.

Sean Francis N. Ballais profile image
That guy who loves working with computers, a bit of photography, gaming, and a whole lot more.