2013-10-01 155 views
-5

计数的字符occurence在接受采访时有人问我这样的问题:从控制台输入流

从像控制台以输入:“欢迎世界”和计数由用户输入的特定字符在该指数多少次(即字符的次数),而无需使用像charAt(int ind)

+4

而你的问题是... –

+7

还有,你试过这么远吗? –

+5

你是否找到了工作? :P – user2339071

回答

7

任何内置的方法给你一个答案盆栽不会帮你的。以下是你如何达到你想要的。尝试自己编码。

  1. 将您的字符串转换为字符数组。
  2. 有一个Map将存储char元素作为键和它的计数值。
  3. 遍历char数组和每个元素,检查它是否已经存在于地图中。
    a。如果存在,则将该元素的值增加1并将其放回地图中。 b。如果不存在,则将该char和1一起作为其计数值插入到地图中。
  4. 继续,直到char数组中有更多的元素。
  5. 该地图现在包含所有字符及其各自的计数。
+0

只有一个提示:直接使用'Map'而不是'HashMap'。有关此主题的更多信息,请参阅http://stackoverflow.com/q/383947/1065197 –

+1

@LuiggiMendoza - 建议采取! :)当Map启动时,我进入了'java'模式,因为我经常使用'Map map = new HashMap()'! – SudoRahul

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); 
     } 
    } 
} 
+2

您正在使用IndexOutOfBoundsException终止您的for循环?大胆的选择! – Henrik