samedi 30 mai 2015

Alles außer Muster in String ersetzen

Hi,

diese Funktion funktioniert, aber kann man das auch "besser" lösen?

Java Code:

  1.  
  2. package sax.test;
  3.  
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6.  
  7. public class Regex {
  8.  
  9.  
  10.  
  11. /**
  12. * input:
  13. * random string, a-z, random length
  14. * and a pattern "abc" for example
  15. * pattern can be a-y, length min: 3 max: string.length()
  16. * output:
  17. * input string with anything but the pattern replaced with Z
  18. *
  19. * example:
  20. * input: "aaaddd", pattern "ddd", output "ZZZddd"
  21. * input: "adddb", pattern "ad", output "ZZddb"
  22. * input: "ccchhhccc", pattern "hhhc", output: "ZZZhhhcZZ"
  23. * input: "jjjiiikkk", pattern "jjj", output: "jjjZZZZZZ"
  24. *
  25. * @param sax_result
  26. * @return
  27. */
  28.  
  29.  
  30. public static void replaceString2(String input, String pattern) {
  31. System.out.println("input: " + input);
  32. StringBuilder tmp = new StringBuilder();
  33.  
  34. for (int n=0; n<= input.length()-1; n++) {
  35. tmp.append('Z');
  36. }
  37.  
  38.  
  39.  
  40. System.out.println("tmp: " + tmp);
  41. ArrayList<Integer> positions_of_pattern = new ArrayList<Integer>();
  42.  
  43. // find all positions of the pattern in string
  44. for (int n=0; n <= input.length()-1-pattern.length()-1; n++) {
  45. int index = input.indexOf(pattern, n);
  46.  
  47. if (index != -1) {
  48. if (! positions_of_pattern.contains(index)) {
  49. positions_of_pattern.add(index);
  50. }
  51. }
  52.  
  53. }
  54.  
  55. System.out.println("position of pattern: " + positions_of_pattern);
  56.  
  57. char[] tmpCharArray = tmp.toString().toCharArray();
  58. char[] patternCharArray = pattern.toCharArray();
  59.  
  60.  
  61. for (int n=0; n<= tmpCharArray.length; n++) {
  62.  
  63. if (positions_of_pattern.size() >= 1) {
  64. if (n == positions_of_pattern.get(0)) {
  65. for (char x: patternCharArray) {
  66. tmpCharArray[n] = x;
  67. n++;
  68. }
  69. positions_of_pattern.remove(0);
  70. }
  71.  
  72. }
  73. }
  74.  
  75. System.out.println("output:");
  76. System.out.println(tmpCharArray);
  77. System.out.println("\n");
  78. }
  79.  
  80.  
  81. public static void main(String[] args) {
  82. ArrayList<String> inputStrings = new ArrayList<String>(Arrays.asList( "bdddb", "dddhhh", "aaadddaddd"));
  83. String pattern = "ddd";
  84. for (String x: inputStrings) {
  85. //System.out.println(replaceString(x));
  86. replaceString2(x, pattern);
  87. }
  88. }
  89. }


Alles außer Muster in String ersetzen

0 commentaires:

Enregistrer un commentaire