简体   繁体   English

如何在不使用s循环的情况下计算字符多次出现在字符串中

[英]how to count many times a character occurs in a string without using s loop

the code below is meant to count each time character 'x' occurs in a string but it only counts once .. 下面的代码用于计算字符串中字符'x'的每次出现,但仅计数一次。

I do not want to use a loop. 我不想使用循环。

public class recursionJava

{

   public static void main(String args[])

   {

      String names = "xxhixx";

      int result = number(names);
      System.out.println("number of x: " + result);
   }

   public static int number (String name)
   {

      int index = 0, result = 0;

      if(name.charAt(index) == 'x')
      {
         result++;
      }
      else
      {
         result = result;
      }
            index++;

      if (name.trim().length() != 0)
      {
        number(name);
      }
      return result;
   }
}

You could do a replacement/removal of the character and then compare the length of the resulting string: 您可以替换/删除字符,然后比较结果字符串的长度:

String names = "xxhixx";
int numX = names.length() - names.replace("x", "").length(); // numX == 4

If you don't want to use a loop, you can use recursion: 如果您不想使用循环,则可以使用递归:

public static int number (String name)
{
    if (name.length () == 0)
        return 0;
    int count = name.charAt(0)=='x' ? 1 : 0;
    return count + number(name.substring(1));
}

从Java 8开始,您可以使用流:

"xxhixx".chars().filter(c -> ((char)c)=='x').count()

Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). 先前的递归答案(来自Eran)是正确的,尽管它在新的Java版本中具有二次复杂性(子字符串在内部复制字符串)。 It can be linear one: 它可以是线性的:

    public static int number(String names, int position) {
    if (position >= names.length()) {
        return 0;
    }

    int count = number(names, position + 1);

    if ('x' == names.charAt(position)) {
        count++;
    }
    return count;
}

Your code does not work because of two things: 您的代码由于两件事而无法工作:

  1. Every time you're calling your recursive method number() , you're setting your variables index and result back to zero. 每次调用递归方法number() ,都将变量index设置为零并将result返回零。 So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far. 因此,该程序将始终停留在第一个字母上,并且还会重置到目前为止已找到的x数的记录。
  2. Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc. 同样, name.trim()在这里几乎没有用,因为此方法仅删除空格字符,例如空格,制表符等。

You can solve both of these problems by 您可以通过以下方式解决这两个问题

  1. making index and result global variables and 制作indexresult全局变量,以及
  2. using index to check whether or not you have reached the end of the String. 使用index来检查您是否已到达String的末尾。

So in the end, a slightly modified (and working) Version of your code would look like this: 因此,最后,经过稍微修改(工作)的代码版本将如下所示:

public class recursionJava {

    private static int index = 0;
    private static int result = 0;

    public static void main(String[] args) {
        String names = "xxhixx";

        int result = number(names);
        System.out.println("number of x: " + result);
    }

    public static int number (String name){
        if(name.charAt(index) == 'x')
            result++;

        index++;

        if(name.length() - index > 0)
            number(name);
        return result;
    }

}

You can use StringUtils.countMatches 您可以使用StringUtils.countMatches

StringUtils.countMatches(name, "x"); StringUtils.countMatches(name,“ x”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM