Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.commons.lang.StringUtils;
- import java.util.LinkedList;
- import java.util.List;
- public class StringHideUtils {
- /**
- * @param str - string to replace
- * @param ch - character for replacement
- * @param n - count of the first characters to show
- * @return
- */
- public static String showFirstChars(String str, char ch, int n) {
- if (str == null || n > str.length()) {
- return str;
- }
- char[] word = hideChars(str.toCharArray(), ch, n, str.length());
- return new String(word);
- }
- /**
- * @param str - string to replace
- * @param ch - character for replacement
- * @param n - count of the last characters to show
- * @return
- */
- public static String showLastChars(String str, char ch, int n) {
- if (str == null || n > str.length()) {
- return str;
- }
- char[] word = hideChars(str.toCharArray(), ch, 0, str.length() - n);
- return new String(word);
- }
- /**
- * @param str - string to replace
- * @param ch - character for replacement
- * @param first - count of the first characters to show
- * @param last - count of the last characters to show
- * @return
- */
- public static String hideMiddleChars(String str, char ch, int first, int last) {
- if (str == null || first > str.length() || last > str.length()) {
- return str;
- }
- Integer[] indexes = findEmptyCharIndex(str);
- str = str.replaceAll("\\s", "");
- char[] word = hideChars(str.toCharArray(), ch, first, str.length() - last);
- return indexes.length == 0 ? new String(word) : mergeWhitespacesToString(word, indexes);
- }
- private static Integer[] findEmptyCharIndex(String str) {
- List<Integer> emptyCharIndex = new LinkedList<>();
- for (int i = 0; i < str.length(); i++) {
- if (str.charAt(i) == ' ') {
- emptyCharIndex.add(i);
- }
- }
- return emptyCharIndex.toArray(new Integer[emptyCharIndex.size()]);
- }
- private static String mergeWhitespacesToString(char[] word, Integer[] whiteSpacesIndexes) {
- LinkedList<Character> charList = new LinkedList<>();
- for (char letter : word) {
- charList.add(letter);
- }
- for (Integer whtIx : whiteSpacesIndexes) {
- charList.add(whtIx, ' ');
- }
- return StringUtils.join(charList.toArray());
- }
- //skip empty char
- private static char[] hideChars(char[] word, char ch, int start, int end) {
- for (int i = start; i < end; i++) {
- word[i] = ch;
- }
- return word;
- }
- }
Add Comment
Please, Sign In to add comment