1

I have a String like this: String sample = "a|b||d|e";
and I'm trying to split the string with tokenizer

StringTokenizer tokenizer = new StringTokenizer(sample, "|");
String a = tokenizer.nextToken();
String b = tokenizer.nextToken();
String c = tokenizer.nextToken();
String d = tokenizer.nextToken();

When I use the above code, the String variable c is assigned to the value d.
StringTokenizer doesn't initialize a null value to String c.

How can we validate and assign default value like - if it is null?

3
  • 1
    A quote from the documentation: "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." Commented Jul 11, 2017 at 7:01
  • 1
    Possible duplicate of Java StringTokenizer.nextToken() skips over empty fields Commented Jul 11, 2017 at 7:01
  • As @1615903 said it is not possible with StringTokenizer. But you can do the same using String using split method. Commented Jul 11, 2017 at 7:11

1 Answer 1

2

As others have said, you can use String#split() on pipe, which would return an entry for the empty match. In the code snippet below, I use streams to map the empty entry into dash per your desired output.

String sample = "a|b||d|e";
String[] parts = sample.split("\\|");
List<String> list = Arrays.asList(parts).stream()
    .map(o -> {
        if (o.equals("")) {
            return "-";
        } else {
            return o;
        }
    }).collect(Collectors.toList());

for (String part : list) {
   System.out.println(part);
}

Output:

a
b
-
d
e

Demo here:

Rextester

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.