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?

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
Kishor kumar R
  • 195
  • 2
  • 17
  • 1
    A quote from the [documentation](https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html): _"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."_ – 1615903 Jul 11 '17 at 07:01
  • 1
    Possible duplicate of [Java StringTokenizer.nextToken() skips over empty fields](https://stackoverflow.com/questions/11409320/java-stringtokenizer-nexttoken-skips-over-empty-fields) – 1615903 Jul 11 '17 at 07:01
  • As @1615903 said it is not possible with `StringTokenizer`. But you can do the same using `String` using `split` method. – Sunil Kanzar Jul 11 '17 at 07:11

1 Answers1

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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360