Search code examples
javastringjava.util.scannercharsequence

Pass a CharSequence to a Scanner in Java


The Scanner class has a constructor taking a String.

Scanner s = new Scanner( myString ) ;

How to feed a CharSequence object to a new Scanner? I could first generate a String from the CharSequence, but that is inefficient and rather silly.

Scanner s = new Scanner( myCharSequence.toString() ) ;  // Workaround, but seems needlessly inefficient to instantiate a `String`. 

I looking for a way to access the CharSequence directly from the Scanner. Something like this:

Scanner s = new Scanner( myCharSequence ) ;  // Use `CharSequence` directly.

The Scanner class also takes a Readable in a constructor. Can a CharSequence be presented as a Readable? Or is there some other workaround?


Solution

  • Given that the constructors only accept String and not the more generic CharSequence, you...can't. Not unless you invoke toString on the CharSequence, anyway, which would get you a String back, which would satisfy the constructor's requirements.

    So, the workaround calling CharSequence::toString as seen in the Question is indeed the way to go:

    new Scanner( myCharSequence.toString() )