【问题标题】:How do I find out the position of a char如何找出字符的位置
【发布时间】:2012-08-27 13:53:35
【问题描述】:

我有一个字符串(“Dinosaur”),但我不知道如何获取字符“o”的位置,是否有可能获得两个位置,例如我的字符串是(“游泳池”)

【问题讨论】:

  • 我只找到了替换字符串中字符的代码,现在我想使用此代码,但如果找不到字符的位置,我将无法使用
  • documentation 是您的朋友。你要找的方法是indexOf

标签: java indexof


【解决方案1】:

对于第一个问题,您可以使用String#indexOf(int) 获取字符串中每个“o”的索引。

int oPos = yourString.indexOf('o');

至于您的第二个问题,可以通过使用String.indexOf(int, int) 的方法获取给定字符的所有位置,跟踪前一个索引,这样您就不会重复搜索字符串的部分。您可以将位置存储在数组或列表中。

【讨论】:

  • KeyEvent.VK_O == 79 == 'O'(大写 O)。只需使用小写字符文字'o'
【解决方案2】:

在循环中使用indexOf

String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
  System.out.println(idx);
  idx = s.indexOf('o', idx + 1);
}

【讨论】:

    【解决方案3】:

    简单地说:

    public static int[] getPositions(String word, char letter)
    {
        List<Integer> positions = new ArrayList<Integer>();
        for(int i = 0; i < word.length(); i++) if(word.charAt(i) == letter) positions.add(i);
    
        int[] result = new int[positions.size()];
        for(int i = 0; i < positions.size(); i++) result[i] = positions.get(i);
    
        return result;
    }
    

    【讨论】:

      【解决方案4】:

      这可能有点过火了,但是嘿;)

      String master = "Pool";
      String find = "o";
      
      Pattern pattern = Pattern.compile(find);
      Matcher matcher = pattern.matcher(master);
      
      String match = null;
      
      List<Integer[]> lstMatches = new ArrayList<Integer[]>(5);
      while (matcher.find()) {
      
          int startIndex = matcher.start();
          int endIndex = matcher.end();
      
          lstMatches.add(new Integer[] {startIndex, endIndex});
      
      }
      
      for (Integer[] indicies : lstMatches) {
      
          System.out.println("Found " + find + " @ " + indicies[0]);
      
      }
      

      给我

      Found o @ 1
      Found o @ 2
      

      很棒的是,你也可以找到“oo”

      【讨论】:

      • 啊,是的,但它也非常非常灵活;)
      • 我不介意人们偶尔会过火,但拼写错误的“嘿”是不可原谅的 :-)
      • @paxdiablo 对不起,我很抱歉,我已经更新了这个最令人发指的错误,我希望你能在你的内心找到它来原谅我 - 我必须有头脑 ; )(不认真,谢谢;))
      【解决方案5】:

      您是否尝试过将 String 转换为 char 数组?

      int counter = 0;
      String input = "Pool";
      for(char ch : input.toCharArray()) {
          if(ch == 'o') {
              System.out.println(counter);
          }
          counter += 1;
      }
      

      【讨论】:

        【解决方案6】:

        试试这个

         String s= "aloooha";
         char array[] = s.toCharArray();
         Stack stack = new Stack();
        
         for (int i = 0; i < array.length; i++) {
            if(array[i] == 'o'){
              stack.push(i);
            }
         }        
         for (int i = 0; i < stack.size(); i++) {
            System.out.println(stack.get(i));
         }
        

        【讨论】:

          猜你喜欢
          • 2019-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-24
          • 2017-11-20
          • 1970-01-01
          相关资源
          最近更新 更多