Skip to content

Instantly share code, notes, and snippets.

@michalbcz
Last active October 26, 2016 09:45
Show Gist options
  • Select an option

  • Save michalbcz/4861a2b8ed73bb73764e909b87664cb2 to your computer and use it in GitHub Desktop.

Select an option

Save michalbcz/4861a2b8ed73bb73764e909b87664cb2 to your computer and use it in GitHub Desktop.
copy pasted strip method from Apache Commons StringUtils - Character#isWhitespace replaced by Character#isSpaceChar (which is unicode aware)
import static org.apache.commons.lang3.StringUtils.isEmpty;
public class StringUtils {
/**
* unicode aware version of Apache Common's StringUtils#strip
*/
public static String strip(String str) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, null);
return stripEnd(str, null);
}
public static String stripStart(String str, String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while ((start != strLen) && Character.isSpaceChar(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
start++;
}
}
return str.substring(start);
}
public static String stripEnd(String str, String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while ((end != 0) && Character.isSpaceChar(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
end--;
}
}
return str.substring(0, end);
}
}
@michalbcz

Copy link
Copy Markdown
Author

or you can use Google Guava

CharMatcher.WHITESPACE.trimFrom(source);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment