I would like to format a number raised to a power using unicode characters.
The thing is that I have to parse first a String containing ^
symbols and the powers next to it
I understand that if, for example I get x^2 to format it I should basically System.out.println("x\u00B2")
for printing x²
What if I get a 2 digit power such as x^23 ?
I have the following code for formatting 1 digit powers:
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9
char[] unicodePowers = {'\u2070','\u00B9','\u00B2','\u00B3','\u2074',
'\u2075','\u2076','\u2077','\u2078','\u2079'};
String[] resultPowers = {"^0","^1","^2","^3","^4","^5","^6","^7","^8","^9"};
for(int i = 0; i < unicodePowers.length; i ){
expression = expression.replace(resultPowers[i],String.valueOf(unicodePowers[i]));
}
I'm not very familiar with formatting Unicode so I don't know if there is a better approach for solving it.
Thanks!
CodePudding user response:
private static final Pattern EXPONENT_PATTERN = Pattern.compile("\\^(\\d )");
private static final String NORMAL_LETTERS = "0123456789";
private static final String SUPERSCRIPT_LETTERS =
"\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079";
public static String styled(String s) {
return EXPONENT_PATTERN.matcher(s).replaceAll(mr -> {
char[] chs = mr.group(1).toCharArray();
for (int i = 0; i < chs.length; i) {
int j = NORMAL_LETTERS.indexOf(chs[i]);
if (j != -1) {
chs[i] = SUPERSCRIPT_LETTERS.charAt(j);
}
}
return new String(chs);
});
}
For letters you may search too, https://unicode-table.com/en/blocks/phonetic-extensions/ However I do not think there are many superscript math operators.