@eagle said:
@endergt said:
return "&#" + (int)s + ";";
Actually this string expression is very inefficient for the purpose at hand.
If I would want a) best performance and b) still quite readable code, I would do this:
<font size="2">class ... {
static final int MAX_INDEX = '>'+1;
static final String[] sc = new String[MAX_INDEX];
static {
sc['>'] = "&#62";
sc['<'] = "&#60";
sc['''] = "&#39";
sc['&'] = "&#38";
sc['"'] = "&#34";
}
String sourceCharacter(char s) {
if (s > MAX_INDEX) {
return null;
} else {
return sc[s];
}
}
}</font>
cu
???
This is a really nice approach, readable and performant, and it will work well after you debug it. MAX_INDEX is misnamed; it's actually the length of the array, not the maximum index. So s > MAX_INDEX is the wrong condition; it should either be s >= MAX_INDEX, or just s >= sc.length, which would have avoided the issue (the array always knows its length; your variable may or may not be right, and in this case it's wrong).
Also, you left the semicolons off of the HTML character entities. With these things fixed, the code is (assuming I can figure out how to post code on this forum software):
<font size="2">
class ... {
static final int MAX_INDEX = (int)'>';
static final String[] sc = new String[MAX_INDEX+1];
static {
sc['>'] = "&#62;";
sc['<'] = "&#60;";
sc['''] = "&#39;";
sc['&'] = "&#38;";
sc['"'] = "&#34;";
}
String sourceCharacter(char s) {
if (s >= sc.length) {
return null;
} else {
return sc[s];
}
}
}</font>