【问题标题】:Check if all characters in string are the same with inbuilt methods without loops检查字符串中的所有字符是否与没有循环的内置方法相同
【发布时间】:2021-06-20 19:50:27
【问题描述】:

如果 String 中的所有字符使用内置方法相同 - 不使用正则表达式、循环或递归,我如何构建返回 TRUE 的 Java 方法?

例子:

aaaaaa --> True
abaaaa --> False
Aaaaaa --> False

【问题讨论】:

  • 取第一个字符,例如在abaaa 中计算str.length() 中有多少个a,如果相等,则包含所有相同的字符,否则return false
  • 为什么没有循环?您必须以某种方式迭代所有字符;递归将是一种糟糕的方式。
  • 我认为没有循环是不可能的。你可能会发现一些花哨的内置方法,但它也会使用自己的一些循环。
  • @AndyTurner 对一个类来说有点挑战,我相信目标是学习内置方法和方法链。

标签: java string character


【解决方案1】:

您可以使用.chars() 将字符串转换为IntStream,并使用.distinct().count() == 1 检查流的不同计数是否为1

String s = "aaaaaa";
boolean isAllCharsSame = s.chars().distinct().count() == 1;

如果字符串s 中的所有字符都相同,则isAllCharsSame 将为true,否则为false

编辑:

String s = "aaaaaa";
boolean isAllCharsSame = s.codePoints().distinct().count() == 1;

.chars() 不适用于像 "???" 这样的 Unicode 代码点,请使用 .codePoints()。感谢@BasilBourque 指出这一点。

【讨论】:

  • "???" 的输入失败。
  • @BasilBourque 我已经更新了答案,谢谢。
【解决方案2】:

您可以使用String.replaceAll()

String s = "aaaaaaa";
boolean same = s.replaceAll("" + s.charAt(0), "").length() == 0;

【讨论】:

    【解决方案3】:

    你完全可以不用循环,使用递归。这很糟糕,但有可能:

    boolean singleChar(String s) {
      // Add check to make sure there is at least one char.
    
      char first = s.charAt(0);
      return singleCharRecursive(first, 1, s);
    }
    
    boolean singleCharRecursive(char first, int idx, String s) {
      return idx >= s.length()
          || (s.charAt(idx) == first && singleCharRecursive (first, idx+1, s));
    }
    

    【讨论】:

      【解决方案4】:

      这是另一个答案

      我相信可能还有另一种选择分析字符串中的第一个字符以查看它们是否都匹配,但是这个可行。

      String t = "aaa";
      char c = t.charAt(0);
      long cnt = t.chars().filter(ch -> ch == c).count();
      System.out.println(cnt==t.length());
      

      【讨论】:

      • 您也可以这样做。 boolean result = t.chars().allMatch(ch -> ch == t.charAt(0));
      【解决方案5】:

      tl;博士

      if ( "???".codePoints().distinct().count() == 1 ) { … }
      

      代码点,不是char

      其他一些答案使用char。不幸的是,char 类型已经过时,甚至无法表示Unicode 中 143,859 个字符的一半。只需尝试使用字符串"???" 而不是"aaa"

      改为使用code point 整数。

      Set < Integer > codePointsDistinct = "aaaaaaa".codePoints().boxed().collect( Collectors.toSet());
      boolean allSameCharacter = ( codePointsDistinct.size() == 1 ) ;
      

      看到code run live at IdeOne.com

      是的

      我们可以通过调用.distinct() 要求流消除重复项来使这一点更加简洁。

      boolean allSameCharacter = ( "???".codePoints().distinct().count() == 1 );
      

      【讨论】:

        【解决方案6】:

        你可以使用replace方法:

        boolean r = "aaaaaaa".replace("a", "").length() == 0;
        System.out.println(r); // true
        

        另见:Easier way to represent indicies in a 2D array

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-27
          • 2013-04-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多