Character counting in String does not work with tabs ('\ t'). Am I using the wrong methods?

I want to read every char in a String. Each char adds 1 to the counter, and tabs should add 4.

My code is:

int counter = 0; for(char c : myString.toCharArray()) { if("\t".equals(""+c)) { counter = counter + 4; } else { counter++; } } 

I made a lot of different lines in a text editor and set the tab to 4. Lines with characters and numbers are not a problem. As soon as I add several tabs between the result, it is always greater by 1. My editor says the line is 100 characters long, but my code is 101. It doesn't matter if there are 2 or 20 tabs in the line. It is always considered too big.

Any ideas or better solutions? Perhaps the methods used cause this behavior?

EDIT: My test lines:

 Line 12: 121 characters ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd Line 13: 120 characters dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd Line 14: 119 characters with tabs kkk Line 15: 120 characters with tabs lkkk 

My code is exactly 121 characters for "Line 12" and 120 for "Line 13". In the line "Line 14" it is 120, and for "Line 15" - 121 characters. I have no idea why. line feeds are ignored.

+5
source share
2 answers

Well, I copied your code and executed it when I could not find any error.

I tried the following code: -

 import java.util.Scanner; public class Alpha{ public static void main(String[] args){ int counter = 0; Scanner s= new Scanner(System.in); System.out.println("Enter a String :- "); String myString=s.nextLine(); for(char c : myString.toCharArray()) { System.out.println(c); if("\t".equals(""+c)) { counter = counter + 4; } else { counter++; } } System.out.println("Counter="+counter); } } 

And every time I got the right conclusion.

SAMPLE OUTPUT RECEIVED :-

 Ram is/t // Comment---> /t represents tab-hit after "is" word R a m i s Counter=10 

So, for me it is being judged correctly. Please check your entrances (whether the line channels / wagon returns are also calculated). Good luck.

+2
source

For a simple string

He works well

 package test; public class Test { public static void main(String[] args) { int counter = 0; String myString = "aghfhg\n \n"; for (char c : myString.toCharArray()) { if ("\t".equals("" + c)) { counter = counter + 4; } else { counter++; } } System.out.println(counter); // output is 13 including 1 space , 1 tab and 2 line characters } } 

Please enter your line

+1
source

All Articles