簡體   English   中英

在Java中將特殊字符計數為空格

[英]Counting special characters as spaces in java

我正在使用JDK 8在MacOS上工作。我想計算給定字符串中特殊字符的數量,但是在給定的代碼中,特殊字符被計為空格。 我該怎么辦?

public static void main(String args[])
{
 String str;
 int lc=0,uc=0,d=0,s=0,spc=0;
 Scanner sc=new Scanner(System.in);
 System.out.print("Enter the string:");
 str=sc.nextLine();

 for(int i=0;i<str.length();i++)
   {
    if(str.charAt(i)>='a' && str.charAt(i)<='z')
    {
    lc++;
    }
    else if(str.charAt(i)>='A' && str.charAt(i)<='Z')
    {
    uc++;
    }
    else if(str.charAt(i)>='0' && str.charAt(i)<='9')
    {
    d++;
    }
    else if(str.charAt(i)>=32)
    {
    s++;
    }
    else if(str.charAt(i)>=33 && str.charAt(i)<=47 || str.charAt(i)==64)
    {
    spc++;
    }
   }
System.out.println("number of small characters in "+str+" are:"+lc);
System.out.println("number of CAPITAL characters in "+str+" are:"+uc);
System.out.println("number of digits in "+str+" are:"+d);
System.out.println("number of Spaces in "+str+" are:"+s);
System.out.println("number of Special characters in "+str+" are:"+spc);
}

這是我得到的輸出:

Enter the string:abc23@#$% 

number of small characters in abc23@#$% are:3

number of CAPITAL characters in abc23@#$% are:0

number of digits in abc23@#$% are:2

number of Spaces in abc23@#$% are:4

number of Special characters in abc23@#$% are:0

它應該顯示4個特殊字符,而不是4個空格。

str.charAt(i)==32更改str.charAt(i)>=32 str.charAt(i)==32

"abc23@#$% "的輸出將是:

number of small characters in abc23@#$%  are:3
number of CAPITAL characters in abc23@#$%  are:0
number of digits in abc23@#$%  are:2
number of Spaces in abc23@#$%  are:1
number of Special characters in abc23@#$%  are:4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM