简体   繁体   中英

Java split by comma in string containing whitespace

I have a below string which I want to split by ',' only and also want to separate 3rd index which is (1005,111222) of each line .

1002,USD,04/09/2019,1005,1,cref,,,,,,,,,
1001,USD,11/04/2018,111222,10,reftpt001,SHA,Remittance Code,BCITIT31745,,,RTGS,,,,

I am using code down below :

List<String> elements = new ArrayList<String>();
List<String> elements2 = new ArrayList<String>();
StringTokenizer st = new StringTokenizer((String) object);
while(st.hasMoreTokens()) {
                    String[] row = st.nextToken().split(",");
                    if (row.length == 5) {
                        elements.add(row[3]);
                    }
                    if (row.length == 12) {
                        elements2.add(row[3]);
                    }
                }

In the above string, There is a space between ' Remittance Code ' but it is splitting till remittance and after that, it counts the code a new line or string. Please advise how can I skip the white space as it is.

There is no apparent need for StringTokenizer here, and the nextToken() call stops at the first space. Instead I suggest calling output.split(",") directly like

String[] row = ((String) object).split("\\s*,\\s*", -1);

And remove the StringTokenizer , note the JavaDoc explicitly says 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.

首先可以拆分,然后使用修剪操作

String stringToSplit= "1001,ZAR,11/04/2018,111222,10,reftpt001,SHA,Remittance Code,BCITIT31745,,,RTGS,,,,"; 
StringTokenizer tokenizer = new StringTokenizer(stringToSplit, ","); 
while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); }

Output :

1001 ZAR 11/04/2018 111222 10 reftpt001 SHA Remittance Code BCITIT31745 RTGS

I tried with this code:

1st approach :

String str = "1001,ZAR,11/04/2018,111222,10,reftpt001,SHA,Remittance Code,BCITIT31745";
String[] words = str.split(",");
for(String word : words) {
   System.out.println(word);
}

2nd approach :

String str = "1001,ZAR,11/04/2018,111222,10,reftpt001,SHA,Remittance Code,BCITIT31745";
StringTokenizer tokenizer = new StringTokenizer(str, ",");
while(tokenizer.hasMoreTokens())
{
  System.out.println(tokenizer.nextToken());
}

Output :

11/04/2018
111222
10
reftpt001
SHA
Remittance Code
BCITIT31745

Hope this helps you. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM