0

String str= -PT31121936-1-0069902679870--BLUECH
I want divide the above string by useing string Tokenize

output like this:
amount=" ";
txnNo = PT31121936;

SeqNo = 1;

AccNo = 0069902679870;

Cldflag=" ";

FundOption= BLUECH;

1 Answers1

0

Solution in Java using String split, it would be better than String tokenizer.

There are two solutions

1) This approach is assuming the input string will be always in a specific order.

2) This approach is more dynamic, where we can accommodate change in the order of the input string and also in the number of parameters. My preference would be the second approach.

public class StringSplitExample {

    public static void main(String[] args) {


        // This solution is based on the order of the input 
        // is Amount-Txn No-Seq No-Acc No-Cld Flag-Fund Option

        String str= "-PT31121936-1-0069902679870--BLUECH";

        String[] tokens = str.split("-");

        System.out.println("Amount :: "+tokens[0]);
        System.out.println("Txn No :: "+tokens[1]);
        System.out.println("Seq No :: "+tokens[2]);
        System.out.println("Acc No :: "+tokens[3]);
        System.out.println("Cld Flag :: "+tokens[4]);
        System.out.println("Fund Option :: "+tokens[5]);
        // End of First Solution            

        // The below solution can take any order of input, but we need to provide the order of input


        String[] tokensOrder = {"Txn No", "Amount", "Seq No", "Cld Flag", "Acc No", "Fund Option"};
        String inputString = "PT31121936--1--0069902679870-BLUECH";

        String[] newTokens = inputString.split("-");
        // Check whether both arrays are having equal count - To avoid index out of bounds exception
        if(newTokens.length == tokensOrder.length) {
            for(int i=0; i<tokensOrder.length; i++) {
                System.out.println(tokensOrder[i]+" :: "+newTokens[i]);
            }
        }

    }
}

Reference: String Tokenizer vs String split Scanner vs. StringTokenizer vs. String.Split

Community
  • 1
  • 1
Clement Amarnath
  • 4,779
  • 1
  • 16
  • 29