1 package be
.nikiroo
.jvcard
.tui
;
3 import java
.text
.Normalizer
;
4 import java
.text
.Normalizer
.Form
;
5 import java
.util
.regex
.Pattern
;
7 import com
.googlecode
.lanterna
.gui2
.LinearLayout
.Alignment
;
9 public class StringUtils
{
10 static private Pattern marks
= Pattern
11 .compile("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");
14 * Fix the size of the given {@link String} either with space-padding or by
18 * the {@link String} to fix
20 * the size of the resulting {@link String} if the text fits or
23 * @return the resulting {@link String} of size <i>size</i>
25 static public String
padString(String text
, int width
) {
26 return padString(text
, width
, true, Alignment
.Beginning
);
30 * Fix the size of the given {@link String} either with space-padding or by
31 * optionally shortening it.
34 * the {@link String} to fix
36 * the size of the resulting {@link String} if the text fits or
39 * cut the {@link String} shorter if needed
41 * align the {@link String} in this position if we have enough
44 * @return the resulting {@link String} of size <i>size</i> minimum
46 static public String
padString(String text
, int width
, boolean cut
,
53 int diff
= width
- text
.length();
57 text
= text
.substring(0, width
);
58 } else if (diff
> 0) {
59 if (diff
< 2 && align
!= Alignment
.End
)
60 align
= Alignment
.Beginning
;
64 text
= text
+ new String(new char[diff
]).replace('\0', ' ');
67 text
= new String(new char[diff
]).replace('\0', ' ') + text
;
72 int pad1
= (diff
) / 2;
73 int pad2
= (diff
+ 1) / 2;
74 text
= new String(new char[pad1
]).replace('\0', ' ') + text
75 + new String(new char[pad2
]).replace('\0', ' ');
85 * Sanitise the given input to make it more Terminal-friendly by removing
86 * combining characters.
89 * the input to sanitise
91 * allow Unicode or only allow ASCII Latin characters
93 * @return the sanitised {@link String}
95 static public String
sanitize(String input
, boolean allowUnicode
) {
96 return sanitize(input
, allowUnicode
, !allowUnicode
);
100 * Sanitise the given input to make it more Terminal-friendly by removing
101 * combining characters.
104 * the input to sanitise
105 * @param allowUnicode
106 * allow Unicode or only allow ASCII Latin characters
107 * @param removeAllAccents
108 * TRUE to replace all accentuated characters by their non
109 * accentuated counter-parts
111 * @return the sanitised {@link String}
113 static public String
sanitize(String input
, boolean allowUnicode
,
114 boolean removeAllAccents
) {
116 if (removeAllAccents
) {
117 input
= Normalizer
.normalize(input
, Form
.NFKD
);
118 input
= marks
.matcher(input
).replaceAll("");
121 input
= Normalizer
.normalize(input
, Form
.NFKC
);
124 StringBuilder builder
= new StringBuilder();
125 for (int index
= 0; index
< input
.length(); index
++) {
126 char car
= input
.charAt(index
);
127 // displayable chars in ASCII are in the range 32<->255,
129 if (car
>= 32 && car
<= 255 && car
!= 127) {
133 input
= builder
.toString();