forked from se-edu/addressbook-level4
-
Notifications
You must be signed in to change notification settings - Fork 18
/
StringUtil.java
68 lines (58 loc) · 2.43 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
59
60
61
62
63
64
65
66
67
68
package seedu.address.commons.util;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.util.AppUtil.checkArgument;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
/**
* 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) {
requireNonNull(sentence);
requireNonNull(word);
String preppedWord = word.trim();
checkArgument(!preppedWord.isEmpty(), "Word parameter cannot be empty");
checkArgument(preppedWord.split("\\s+").length == 1, "Word parameter should be a single word");
String preppedSentence = sentence;
String[] wordsInPreppedSentence = preppedSentence.split("\\s+");
return Arrays.stream(wordsInPreppedSentence)
.anyMatch(preppedWord::equalsIgnoreCase);
}
/**
* Returns a detailed message of the t, including the stack trace.
*/
public static String getDetails(Throwable t) {
requireNonNull(t);
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return t.getMessage() + "\n" + sw.toString();
}
/**
* Returns true if {@code s} represents a non-zero unsigned integer
* e.g. 1, 2, 3, ..., {@code Integer.MAX_VALUE} <br>
* Will return false for any other non-null string input
* e.g. empty string, "-1", "0", "+1", and " 2 " (untrimmed), "3 0" (contains whitespace), "1 a" (contains letters)
* @throws NullPointerException if {@code s} is null.
*/
public static boolean isNonZeroUnsignedInteger(String s) {
requireNonNull(s);
try {
int value = Integer.parseInt(s);
return value > 0 && !s.startsWith("+"); // "+1" is successfully parsed by Integer#parseInt(String)
} catch (NumberFormatException nfe) {
return false;
}
}
}