-6

In an interview I was asked a question like:

Take an input from console like: "welcome to world" and count a particular character entered by the user at which index and how many times(i.e. occurance of the character) without using any built-in methods like charAt(int ind) etc.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

2 Answers2

7

Giving you a potted answer won't help you at all. Here's how you can achieve what you want. Try to code it yourself.

  1. Convert your String to a Character Array.
  2. Have a Map which would store the char element as the key and its count as the value.
  3. Iterate over the char array and for each element, check if its already existing in the map.
    a. If it exists, increment the value for that element by 1 and put it back in the map.
    b. If it doesn't, insert that char along with 1 as its count value in the map.
  4. Continue till there are more elements in the char array.
  5. The map now has all the char along with their respective counts.
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • Just one tip: use a `Map` instead of a `HashMap` directly. Refer to http://stackoverflow.com/q/383947/1065197 for more info regarding this topic – Luiggi Mendoza Oct 01 '13 at 05:42
  • 1
    @LuiggiMendoza - Suggestion taken! :) I went into the `java` mode when the Map came up, as I'm tuned to using the `Map map = new HashMap()` more often than not! – Rahul Oct 01 '13 at 05:45
0
import java.io.Console;
class dev
{
    public static void main(String arg[])
    {
        Console c=System.console();
        String str=c.readLine();
        System.out.println(str);
        int times=0;
        //find c character 
        char find='c';
        char strChar[]=str.toCharArray();
        System.out.print("positions of char c in the string :");
        try
        {
            for (int i=0; ;i++ )
            {
                if(strChar[i]==find)
                {
                    System.out.print((i-1)+", ");times++;
                }
            }   
        }
        catch (Exception e)
        {
            System.out.println("\n"+"The no. of times c occur : "+times);
        }
    }
}
Michaël
  • 3,679
  • 7
  • 39
  • 64
Dev
  • 3,410
  • 4
  • 17
  • 16