Don't trim tab(\t) from start/end of a String in JAVA

Bhavesh :

I have an input stream which has fields separated by tab(\t) which looks like this

String str = "  acc123\tdpId123\t2011-01-01\t2022-01-01\[email protected]\tIN\t1233\tSOMETHING      ";

which works fine when I do str = str.trim(); and

strArray = str.split("\t", -1); 
strArray=["acc123","dpId123","2011-01-01","2022-01-01","[email protected]","IN","1233","SOMETHING"] will give size as 8 

But last field in the input record is not mandatory and can be skipped.

So the input can look like this too.

 String str1 = "acc123\tdpId123\t2011-01-01\t2022-01-01\[email protected]\tIN\t1233\t";

but in this case last field should be empty but when I use this string after trim and split my size is 7

str1 = str1.trim();      
strArray = str1.split("\t", -1); 
      strArray=["acc123","dpId123","2011-01-01","2022-01-01","[email protected]","IN","1233"]will give size as 7

But I want

strArray=["acc123","dpId123","2011-01-01","2022-01-01","[email protected]","IN","1233",""]

How can I avoid this situation?

Mushif Ali Nawaz :

There you go:

String str1 = "   acc123\tdpId 123\t201 1-01-01\t2022-01-01\[email protected]\tIN\t1233\t";
str1 = str1.replaceAll("^[ ]+", ""); // removing leading spaces
str1 = str1.replaceAll("[ ]+$", ""); // removing trailing spaces
String[] split = str1.split("\t", -1);

System.out.println(Arrays.toString(split));
System.out.println(split.length);

String#trim method also removes \t. To handle that I have removed only the leading and trailing spaces using regex.

Output:

[acc123, dpId 123, 201 1-01-01, 2022-01-01, [email protected], IN, 1233, ]
8

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310990&siteId=1