简体   繁体   English

如何在Java中计算@,#,+等符号的数量

[英]How to count number of symbols like @,#,+ etc in Java

I'm trying to write a code to count number of letters,characters,space and symbols in a String . 我正在尝试编写代码以计算String的字母,字符,空格和符号的数量。 But I don't know how to count Symbols. 但是我不知道如何计算符号。

Is there any such function available in java? java中有可用的此类功能吗?

That very much depends on your definition of the term symbol . 这很大程度上取决于您对“ 符号 ”一词的定义

A straight forward solution could be something like 直接的解决方案可能是这样的

Set<Character> SYMBOLS = Set.of('@', ' ', ....
for (int i=0; i < someString.length(); i++} {
  if (SYMBOLS.contains(someString.charAt(i)) { 

That iterates the chars someString , and checks each char whether it can be found within that predefined SYMBOLS set. 迭代chars someString ,并检查每个字符是否可以在该预定义的SYMBOLS集中找到。

Alternatively, you could use a regular expression to define "symbols", or, you can rely on a variety of existing definitions. 另外,您可以使用正则表达式定义“符号”,或者可以依赖各种现有定义。 When you check the regex Pattern language for java, you can find 当您检查Java的正则表达式模式语言时,可以找到

\w  A word character: [a-zA-Z_0-9]
\W  A non-word character: [^\w]

for example. 例如。 And various other shortcuts that denote this or that set of characters already. 各种其他快捷方式已经表示了这个或那个字符集。

Please post what you have tried so far 请发布您到目前为止尝试过的内容

If you need the count of individual characters - you better iterate the string and use a map to track the character with its count 如果您需要单个字符的计数-最好对字符串进行迭代,并使用映射图来跟踪字符及其计数

Or 要么

You can use a regex if just the overall count would enough like below 如果只需要总数,您可以使用正则表达式,如下所示

while (matcher.find() ) {count++} 

One way of doing it would be to just iterate over the String and compare each character to their ASCII value 一种实现方法是只遍历String并将每个字符与其ASCII值进行比较

String str = "abcd!@#";
        for(int i=0;i<str.length();i++)
        {
            if(33==str.charAt(i))
                System.out.println("Found !");
        }

lookup here for ASCII values https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html 在此处查找ASCII值https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

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

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