cyrus
cyrus

Reputation: 51

Splitting strings with scanner

I am trying to split a string into two others with the Scanner in Java. It doesn't seem to be working. I can only find examples through Google where Scanner is used to read console input. I worked out the way I'm doing things from the manual for the Scanner and I'm not sure what I've got wrong.

String elem = "hello.there";
Scanner s = new Scanner(elem);
s.useDelimiter(".");
String first = s.next();
String second = s.next();

First and second are showing up blank, I'm not sure why.

Upvotes: 0

Views: 495

Answers (3)

Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

String first = s.hasNext(); returns boolean so you can't asssign it to a string.

You need

String first = s.next();

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You need to scape the period (.):

s.useDelimiter("\\.");

and then use next() which returns the next complete token, since hasNext() returns a boolean representinf if the scanner has another token in its input:

String first = s.next();
String second = s.next();

Upvotes: 4

Kanaiya Katarmal
Kanaiya Katarmal

Reputation: 6108

import java.util.Scanner;

public class TokenizeUsingScanner {


/**
 * This java sample code shows how to split
 * String value into tokens using
 * Scanner. This program tokenize
 * the input string base on the delimiter
 * set by calling the useDelimiter method
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String input = "hello.there";
    Scanner s = new Scanner(input);
    s.useDelimiter("\\.");
    while(s.hasNext()){
        System.out.println(s.next());
    }
}
}

Upvotes: 2

Related Questions