I want to count every char in a String. Every char adds 1 to a 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've made a lot different lines in a text editor and set tab space to 4. Lines with chars and numbers are no problem. As soon as I add a few tabs in between the result is always greater by 1. My editor says that the line is 100 characters long but my code counts 101. It doesn't matter if there are 2 or 20 tabs in a line. It counts always 1 too much.
Any ideas or better solutions? Maybe the used methods cause this behavior?
EDIT: My testing 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 counts exactly 121 characters for 'Line 12' and 120 for 'Line 13'. For 'Line 14' it counts 120 and for 'Line 15' 121 characters. I have no idea why. line-feeds get ignored.
Well, I copied your code and executed it,once when I couldn't find any mistake.
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, I received the correct output every time.
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 evaluating correctly. Please check your inputs(whether line-feeds/carriage-returns are also being counted). Good luck.
For simple String
It is running good
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 provide your String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With