Guest User

Untitled

a guest
May 25th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. import org.apache.commons.lang.StringUtils;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.List;
  5.  
  6. public class StringHideUtils {
  7.  
  8. /**
  9. * @param str - string to replace
  10. * @param ch - character for replacement
  11. * @param n - count of the first characters to show
  12. * @return
  13. */
  14. public static String showFirstChars(String str, char ch, int n) {
  15. if (str == null || n > str.length()) {
  16. return str;
  17. }
  18. char[] word = hideChars(str.toCharArray(), ch, n, str.length());
  19. return new String(word);
  20. }
  21.  
  22.  
  23. /**
  24. * @param str - string to replace
  25. * @param ch - character for replacement
  26. * @param n - count of the last characters to show
  27. * @return
  28. */
  29. public static String showLastChars(String str, char ch, int n) {
  30. if (str == null || n > str.length()) {
  31. return str;
  32. }
  33. char[] word = hideChars(str.toCharArray(), ch, 0, str.length() - n);
  34. return new String(word);
  35. }
  36.  
  37.  
  38. /**
  39. * @param str - string to replace
  40. * @param ch - character for replacement
  41. * @param first - count of the first characters to show
  42. * @param last - count of the last characters to show
  43. * @return
  44. */
  45. public static String hideMiddleChars(String str, char ch, int first, int last) {
  46. if (str == null || first > str.length() || last > str.length()) {
  47. return str;
  48. }
  49. Integer[] indexes = findEmptyCharIndex(str);
  50. str = str.replaceAll("\\s", "");
  51.  
  52. char[] word = hideChars(str.toCharArray(), ch, first, str.length() - last);
  53.  
  54. return indexes.length == 0 ? new String(word) : mergeWhitespacesToString(word, indexes);
  55. }
  56.  
  57. private static Integer[] findEmptyCharIndex(String str) {
  58. List<Integer> emptyCharIndex = new LinkedList<>();
  59. for (int i = 0; i < str.length(); i++) {
  60. if (str.charAt(i) == ' ') {
  61. emptyCharIndex.add(i);
  62. }
  63. }
  64. return emptyCharIndex.toArray(new Integer[emptyCharIndex.size()]);
  65. }
  66.  
  67. private static String mergeWhitespacesToString(char[] word, Integer[] whiteSpacesIndexes) {
  68. LinkedList<Character> charList = new LinkedList<>();
  69. for (char letter : word) {
  70. charList.add(letter);
  71. }
  72. for (Integer whtIx : whiteSpacesIndexes) {
  73. charList.add(whtIx, ' ');
  74. }
  75. return StringUtils.join(charList.toArray());
  76. }
  77.  
  78. //skip empty char
  79. private static char[] hideChars(char[] word, char ch, int start, int end) {
  80. for (int i = start; i < end; i++) {
  81. word[i] = ch;
  82. }
  83. return word;
  84. }
  85. }
Add Comment
Please, Sign In to add comment