-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTexttools.java
More file actions
94 lines (75 loc) · 2.42 KB
/
Texttools.java
File metadata and controls
94 lines (75 loc) · 2.42 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* TextTools.java
* @author Herb Wolfe Jr <hwolfe71@gmail.com>
*
* Implementation of the TextToolsInterface
*/
import java.util.*;
import static java.lang.Character.*;
public class Texttools {
// number of letters, and the ascii offsets for upper/lower case letters
private static int ALPHAS = 26;
private static int UPPEROFFSET = 65;
private static int LOWEROFFSET = 97;
/**
* Get the position of a given character in the alphabet
* @param char - the character
* @return int - the position of the letter in the alphabet or 0, if it
* isn't a letter
*/
private static int getAlphaPos(char c) {
int pos = -1;
if (isLetter(c)) {
pos = (int)c - (isUpperCase(c) ? UPPEROFFSET : LOWEROFFSET);
}
return pos;
}
/**
* counts the number of each letter in a given string
* @param String - the string in which to count the letters
* @return int[26] - an array containing the number of each letter
*/
public static int[] getLetterCount(String str) {
int[] count = new int[ALPHAS];
for (char ch : str.toCharArray()) {
int l = getAlphaPos(ch);
if (l >= 0) {
++count[l];
}
}
return count;
}
/**
* Counts the number of words in a given string
* A word in this case consists of letters separated by non-letters
* @param String - the string in which to count the words
* @return int - the number of words
*/
public static int getWordCount(String str) {
int count = 0;
boolean wasPrevLetter = false;
for (char ch : str.toCharArray()) {
if (isLetter(ch) && !wasPrevLetter) { count++; }
wasPrevLetter = isLetter(ch);
}
return count;
}
/**
* Determines if the string is a palindrome
* @param String - the string to check
* @return boolean - if the string is a palindrome
*/
public static boolean isPalindrome(String str) {
String sb = str.replaceAll("[^a-zA-z]","");
String rev = reverseString(sb);
return rev.equalsIgnoreCase(sb);
}
/**
* Reverses a string
* @param String - the string to reverse
* @return String - the reversed string
*/
public static String reverseString(String str) {
return new StringBuffer(str).reverse().toString();
}
}