forked from nus-cs2103-AY1617S2/addressbook-level4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringUtil.java
58 lines (50 loc) · 2.07 KB
/
StringUtil.java
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
package seedu.address.commons.util;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Helper functions for handling strings.
*/
public class StringUtil {
/**
* Returns true if the {@code sentence} contains the {@code word}.
* Ignores case, but a full word match is required.
* <br>examples:<pre>
* containsWordIgnoreCase("ABc def", "abc") == true
* containsWordIgnoreCase("ABc def", "DEF") == true
* containsWordIgnoreCase("ABc def", "AB") == false //not a full word match
* </pre>
* @param sentence cannot be null
* @param word cannot be null, cannot be empty, must be a single word
*/
public static boolean containsWordIgnoreCase(String sentence, String word) {
assert word != null : "Word parameter cannot be null";
assert sentence != null : "Sentence parameter cannot be null";
String preppedWord = word.trim();
assert !preppedWord.isEmpty() : "Word parameter cannot be empty";
assert preppedWord.split("\\s+").length == 1 : "Word parameter should be a single word";
String preppedSentence = sentence;
String[] wordsInPreppedSentence = preppedSentence.split("\\s+");
for (String wordInSentence: wordsInPreppedSentence) {
if (wordInSentence.equalsIgnoreCase(preppedWord)) return true;
}
return false;
}
/**
* Returns a detailed message of the t, including the stack trace.
*/
public static String getDetails(Throwable t) {
assert t != null;
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return t.getMessage() + "\n" + sw.toString();
}
/**
* Returns true if s represents an unsigned integer e.g. 1, 2, 3, ... <br>
* Will return false if the string is:
* null, empty string, "-1", "0", "+1", and " 2 " (untrimmed) "3 0" (contains whitespace).
* @param s Should be trimmed.
*/
public static boolean isUnsignedInteger(String s) {
return s != null && s.matches("^0*[1-9]\\d*$");
}
}