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?
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() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With