Heading

Tuesday, March 19, 2013

Letter occurances in a String in java

public class LetterCount {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
String str="this is bangalore";
char[] c=str.toCharArray();
int count=0,i=0,j=0,k=0,totalletters=0;
for(i=0;i<str.length();i++)
{
    boolean flag=true;
    for(k=0;k<i;k++)
    {
        if(c[k]==(str.charAt(i)))
                flag=false;
               
    }
    if(flag)
    {
        for(j=0;j<str.length();j++)
        {
            if(c[j]==c[i])
                count++;
        }
        System.out.println((str.charAt(i))+ " "+count);
        totalletters++;
    }
   
    count=0;
}
System.out.print("The total letters are:"+totalletters);
    }

}

1 comment:

  1. Expected out put
    t 1
    h 1
    i 2
    s 2
    2
    b 1
    a 2
    n 1
    g 1
    l 1
    o 1
    r 1
    e 1
    The total letters are:13

    ReplyDelete