【问题标题】:Is there a better way to check string for any numbers in it?有没有更好的方法来检查字符串中的任何数字?
【发布时间】:2017-09-23 20:50:42
【问题描述】:

基本上,我被要求编写一个程序来检查一个数字在字符串中出现的次数并将其打印出来。这就是我所拥有的

    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    System.out.println("Please enter your string");
    String s = input.readLine();
    /*System.out.println("Please enter the chracter you are looking for");
    char c = (char)input.read();*/
    char one = '1';
    char two = '2';
    char three = '3';
    char four = '4';
    char five = '5';
    char six = '6';
    char seven = '7';
    char eight = '8';
    char nine = '9';
    char zero= '0';
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
    if( s.charAt(i) == one || s.charAt(i) == two || s.charAt(i) == three || s.charAt(i) == four || 
 s.charAt(i) == five || s.charAt(i) == six || s.charAt(i) == seven 
 || s.charAt(i) == eight || s.charAt(i) == nine || s.charAt(i) == zero ) {
        counter++;


    } 


}

有没有更快、更好的方法来做到这一点?我尝试了另一种方法,但出现了这个错误

Error: The operator || is undefined for the argument type(s) boolean, char

【问题讨论】:

  • 请为编程语言添加标签。

标签: java string numbers counter


【解决方案1】:

您可以查看Java中的Character.isDigit()方法,而不是自己在代码中声明数字。这将使代码更清晰。没有其他更快的方法可以做到这一点。

如果您想计算每个数字的出现次数,一种简单的方法是使用 Java Maps。您可以从here阅读有关地图的基本教程。

【讨论】:

    【解决方案2】:

    这在 c# 中有效

    foreach (char c in str)
        {
            if (c >= '0' && c <= '9')
                counter++;
        }
    

    【讨论】:

    • OP 寻找 java 的解决方案。
    【解决方案3】:

    您可以使用字符的十进制值(定义在ASCII table

    String s = "abc123def456";
    int cpt = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
            cpt++;
        }
    }
    System.out.println(cpt); // 6
    

    你也可以使用Character::isDigit方法

    if (Character.isDigit(s.charAt(i))) {
        cpt++;
    }
    

    编辑:

    如果您使用的是 Java 8+,您可以将字符串转换为字符流,应用过滤器来保留数字,然后计算其中的元素数。

    long nbDigits = s.chars()
        .filter(Character::isDigit) // If the character is a digit (= the isDigit() method returns true) it's kept in the stream
        .count();
    System.out.println(nbDigits); // 6
    

    【讨论】:

      【解决方案4】:

      有没有更快更好的方法来做到这一点

      您的方法绝对正确,几乎最快!你可以让它更具可读性。

      我认为O(n) 的所有语言的通用算法都是相同的:

      1. 找到数字字符时循环数组并递增计数器。

      你的方法是绝对正确的,而且几乎是最快的!注意:我真的认为两次比较和九次比较之间的速度非常非常小,我们不应该关心它)你所能做的就是把它写成尽可能少的代码行。您可以进行以下更正:

      1. char 在 JVM 中是整数,0-9 的 ASCII 码是 0x30-0x39,因此您可以从 == 移动到 ch &gt;= '0' &amp;&amp; ch &lt;= '9'
      2. 字符类包含特殊的检查方法:Character.isDigit(ch)
      3. 对于 java 8,您可以使用 Streams 而不是手动 for...each

      不使用流(普通的旧 java)我认为这种方法提供了最大的速度并减少了内存对象

      public int countDigits(String str) {
          int count = 0;
      
          for(int i = 0; i < str.length(); i++)
              if(Character.isDigit(str.charAt(i)))
                  count++;
      
          return count;
      }
      

      使用流(来自 java 8)。看起来不错,比前面的例子运行得慢了一点,并且在内存中创建了一些额外的对象。

      public int countDigits(String str) {
          // could be a little bit slower, because additional objects are created inside
          return (int)str.chars().filter(Character::isDigit).count();
      }
      

      P.S. 如果你想展示你的技能,普通的旧 java 变体更可取。在工作代码中,两个变体是相等的。

      P.P.S. 实际上String.toCharArray()str.chars() 看起来更优雅,甚至比str.charAr(int) 执行得更少,因为它们在内存中创建了额外的对象,但str.charAr(int) 直接使用内部数组。但我在实际应用中没有遇到任何方法的问题。

      【讨论】:

      • 您的第一个声明是错误的。 OPs 代码对每个 i 调用 charAt(i) 十次。如果您认为这是“最大速度”,那么您和我对这两个词的含义会有很大不同。
      • @GhostCat +1。同意你。这不是绝对正确的。我修改了我的笔记。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2021-10-08
      • 1970-01-01
      相关资源
      最近更新 更多