String Tokenizer requiremen

时间:2015-10-29 06:33:43

标签: string tokenize

String str = -PT31121936-1-0069902679870 - BLUECH
我想通过使用字符串Tokenize

来划分上面的字符串

输出如下:
amount =“”;
txnNo = PT31121936;

SeqNo = 1;

AccNo = 0069902679870;

Cldflag =“”;

FundOption = BLUECH;

1 个答案:

答案 0 :(得分:0)

使用String split的Java解决方案,它会比String tokenizer更好。

有两种解决方案

1)这种方法假设输入字符串将始终按特定顺序排列。

2)这种方法更加动态,我们可以按照输入字符串的顺序以及参数的数量来适应变化。我的偏好是第二种方法。

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]);
            }
        }

    }
}

参考:String Tokenizer vs String split Scanner vs. StringTokenizer vs. String.Split