1 /***
2 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3 */
4 package net.sourceforge.pmd.util;
5
6 public class StringUtil {
7
8 private static final String[] ENTITIES;
9
10 static {
11 ENTITIES = new String[256 - 126];
12 for (int i = 126; i <= 255; i++) {
13 ENTITIES[i - 126] = "&#" + i + ';';
14 }
15 }
16
17 public static String replaceString(String d, char oldChar, String newString) {
18 String fixedNew = newString;
19 if (fixedNew == null) {
20 fixedNew = "";
21 }
22 StringBuffer desc = new StringBuffer();
23 int index = d.indexOf(oldChar);
24 int last = 0;
25 while (index != -1) {
26 desc.append(d.substring(last, index));
27 desc.append(fixedNew);
28 last = index + 1;
29 index = d.indexOf(oldChar, last);
30 }
31 desc.append(d.substring(last));
32 return desc.toString();
33 }
34
35 public static String replaceString(String inputString, String oldString, String newString) {
36 String fixedNew = newString;
37 if (fixedNew == null) {
38 fixedNew = "";
39 }
40 StringBuffer desc = new StringBuffer();
41 int index = inputString.indexOf(oldString);
42 int last = 0;
43 while (index != -1) {
44 desc.append(inputString.substring(last, index));
45 desc.append(fixedNew);
46 last = index + oldString.length();
47 index = inputString.indexOf(oldString, last);
48 }
49 desc.append(inputString.substring(last));
50 return desc.toString();
51 }
52
53 /***
54 * Appends to a StringBuffer the String src where non-ASCII and
55 * XML special chars are escaped.
56 *
57 * @param buf The destination XML stream
58 * @param src The String to append to the stream
59 */
60 public static void appendXmlEscaped(StringBuffer buf, String src) {
61 appendXmlEscaped(buf, src, System.getProperty("net.sourceforge.pmd.supportUTF8", "no").equals("yes"));
62 }
63
64 private static void appendXmlEscaped(StringBuffer buf, String src, boolean supportUTF8) {
65 char c;
66 for (int i = 0; i < src.length(); i++) {
67 c = src.charAt(i);
68 if (c > '~') {
69 if (!supportUTF8) {
70 if (c <= 255) {
71 buf.append(ENTITIES[c - 126]);
72 } else {
73 buf.append("&u").append(Integer.toHexString(c)).append(';');
74 }
75 } else {
76 buf.append(c);
77 }
78 } else if (c == '&')
79 buf.append("&");
80 else if (c == '"')
81 buf.append(""");
82 else if (c == '<')
83 buf.append("<");
84 else if (c == '>')
85 buf.append(">");
86 else
87 buf.append(c);
88 }
89 }
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119 }