-
Notifications
You must be signed in to change notification settings - Fork 501
Expand file tree
/
Copy pathCountSpecialCharacter.java
More file actions
38 lines (31 loc) · 1.08 KB
/
CountSpecialCharacter.java
File metadata and controls
38 lines (31 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Counting a number of Special Character in a given string
* this logic totally works on ascii values
*
* Enter a String to Count Number of Special Characters: Hell# Wor$$
* Number of Special Characters (including whitespaces): 4
*
*/
import java.util.Scanner;
public class CountSpecialCharacter
{
public static int getNumOfSpecialCharacters(String text)
{
int count=1;
int specialCharacters = 0;
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if(ch>=32 && ch<=47 || ch>=58 && ch<=64 || ch>=91 && ch<=96 || ch>=123 && ch<=126) {
specialCharacters += count;
}
}
return specialCharacters;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String to Count Number of Special Characters: ");
String str = in.nextLine();
int result = getNumOfSpecialCharacters(str);
System.out.println("Number of Special Characters (including whitespaces): " +result);
}
}