我想要一个包含Unicode字符串的列表,但我想知道是否可以使用for循环,而不是手动添加9个变量。我尝试了以下代码,但没有成功。
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add("u003" + i + "u20E3");
}
我的IDEA给了我一个"非法unicode转义"错误
还有其他方法可以做到这一点吗?
将数字转换为字符串中字符的最简单方法可能是使用格式化程序,通过string.format:
List<String> reactions = new ArrayList<>();
for (int i = 1; i < 10; i++) {
reactions.add(String.format("%cu20e3", 0x0030 + i));
}
假设要显示字符\u003i,i
从1到9,并且\u20E3,请记住字符就像一个数字,可以用于数学运算。
- 获取字符
u0030
:'u0030'
- 添加i:
'u0030' + i
- 将新字符与另一个连接起来(作为字符串(
然后打印结果:
System.out.println((char)('u0030' + i) + "u20E3");