gpt4 book ai didi

java - java中特殊字符算作空格

转载 作者:行者123 更新时间:2023-12-02 01:32:48 25 4
gpt4 key购买 nike

我正在 MacOS 上工作,使用 JDK 8。我想计算给定字符串中特殊字符的数量,但在给定代码中,特殊字符被计为空格。我该怎么办?

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

"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

关于java - java中特殊字符算作空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57545893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com