JavaAlgorithms/Others/CountChar.java

44 lines
918 B
Java
Raw Normal View History

2017-07-08 09:12:14 +08:00
import java.util.Scanner;
/**
* @author Kyler Smith, 2017
*
* Implementation of a character count.
* (Slow, could be improved upon, effectively O(n).
* */
public class CountChar {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your text: ");
String str = input.nextLine();
2018-01-24 23:57:30 +08:00
input.close();
2017-07-08 09:12:14 +08:00
System.out.println("There are " + CountCharacters(str) + " characters.");
}
2017-08-03 02:10:09 +08:00
2017-07-08 09:12:14 +08:00
/**
* @param str: String to count the characters
*
* @return int: Number of characters in the passed string
* */
public static int CountCharacters(String str) {
int count = 0;
2017-08-03 02:10:09 +08:00
if(str == "" || str == null) //Exceptions
{
return 0;
}
2017-07-08 09:12:14 +08:00
2017-08-03 02:10:09 +08:00
for(int i = 0; i < str.length(); i++) {
if(!Character.isWhitespace(str.charAt(i))) {
2017-07-08 09:12:14 +08:00
count++;
2017-08-03 02:10:09 +08:00
}}
2017-07-08 09:12:14 +08:00
return count;
}
}