繁体   English   中英

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

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

下面的代码用于计算字符串中字符'x'的每次出现,但仅计数一次。

我不想使用循环。

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;
   }
}

您可以替换/删除字符,然后比较结果字符串的长度:

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

如果您不想使用循环,则可以使用递归:

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()

先前的递归答案(来自Eran)是正确的,尽管它在新的Java版本中具有二次复杂性(子字符串在内部复制字符串)。 它可以是线性的:

    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;
}

您的代码由于两件事而无法工作:

  1. 每次调用递归方法number() ,都将变量index设置为零并将result返回零。 因此,该程序将始终停留在第一个字母上,并且还会重置到目前为止已找到的x数的记录。
  2. 同样, name.trim()在这里几乎没有用,因为此方法仅删除空格字符,例如空格,制表符等。

您可以通过以下方式解决这两个问题

  1. 制作indexresult全局变量,以及
  2. 使用index来检查您是否已到达String的末尾。

因此,最后,经过稍微修改(工作)的代码版本将如下所示:

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;
    }

}

您可以使用StringUtils.countMatches

StringUtils.countMatches(name,“ x”);

暂无
暂无

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

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