0

I am spliting the String by tab like

String s = "1"+"\t"+2+"\t"+3+"\t"+"4";
System.out.println("length : "+ s.split("\\t").length);

In this case i get the length 4. But if i remove the last element 4 & give only blank, like

String s = "1"+"\t"+2+"\t"+3+"\t"+"";
System.out.println("Length : "+ s.split("\\t").length);

In this case i got the output 3. it means this is not calculating last tab. In below case also, i need the length 4. This scenario i am using in my project & getting undesired result. So please suggest me, How to calculate the entire length of tab delimited string, whether the last element is also blank. Such as, if the case is,

String s = "1"+"\t"+2+"\t"+3+"\t"+"";
System.out.println("Length : "+ s.split("\\t").length);

then the answer should be 4 & if the case is,

String s = "1"+"\t"+2+"\t"+3+"\t"+"" + "\t"+ "";
System.out.println("Length : "+ s.split("\\t").length);

then the answer should be 5.

Please provide me the appropriate answer.

  • 1
    Instead of splitting the string and counting the length of the split array, why not just iterate over the string, and count the tabs? You can use the `String.matches()` method for every character and find the answer that way. – Hans Petter Taugbøl Kragset Aug 18 '14 at 10:44
  • If you expect 5, do `s.split("\t", 5)`. Then it will give 5 on 4 tabs, and 3 on two tabs. Also only one backslash is needed. – Joop Eggen Aug 18 '14 at 10:49

1 Answers1

0

To prevent split from removing trailing empty spaces you need to use split(String regex, int limit) with negative limit value like

split("\t", -1)
Pshemo
  • 122,468
  • 25
  • 185
  • 269