java - Counting chars in String doesn't work with tabs ('\t'). Am I using wrong methods? -


i want count every char in string. every char adds 1 counter , 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 lot different lines in text editor , set tab space 4. lines chars , numbers no problem. add few tabs in between result greater 1. editor says line 100 characters long code counts 101. doesn't matter if there 2 or 20 tabs in line. counts 1 much.

any ideas or better solutions? maybe used methods cause behavior?

edit: testing lines:

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

my code counts 121 characters 'line 12' , 120 'line 13'. 'line 14' counts 120 , 'line 15' 121 characters. have no idea why. line-feeds ignored.

well, copied code , executed it,once when couldn't find mistake.

i tried 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 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, received correct output every time.

sample output received :-

ram is/t              //  comment---> /t represents tab-hit after "is" word  r m  s  counter=10 

so,for me ,it evaluating correctly. please check inputs(whether line-feeds/carriage-returns being counted). luck.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -