java - 如何用 unicode 字符替换字符串
问题描述
我打算用普通字符串替换字符串为分割字符串,但是普通字符串之间的长度差异为 62,分割长度结果为 117,所以当我们写 'a' 按钮时它不会更改为 '' 还有另一种更容易编写替换字符串的方法吗?
public static String doublestruck(String input){
String normal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String split = "ℂℍℕℙℚℝℤ";
String output = "";
char letter;
for(int i = 0; i < input.length(); i++){
letter = input.charAt(i);
int a = normal.indexOf(letter);
output += (a != -1) ? split.charAt(a):letter;
}
return new StringBuilder(output).toString();
}
解决方案
(U+1D7DC) 之类的字母不在基本多语言窗格中,因此在 Java 中占用两个char
值。
而不是charAt
您需要使用codePointAt
并找到您需要使用的正确偏移量,offsetByCodePoint
而不是直接使用相同的索引。所以split.charAt(a)
需要换成split.codePointAt(spli.offsetByCodePoint(0, a))
。
推荐阅读
- ocaml - 递归函数和“输入”错误
- spring-security - Spring Security:hasAuthority、hasRole 和 PreAuthorize 不起作用
- python - Python:将多个变量分配给另一个变量意味着什么
- c# - 确实选择了数据库时,MySQL(ADO.NET)给出“未选择数据库”错误
- python - Pipenv "ModuleNotFoundError: No module named 'pip'" 升级到 python3.7 后
- ruby-on-rails - 在 rails yml 文件中存储密码的最佳解决方案是什么?
- git - git ls-files --stage 即使在提交后也显示文件
- ruby-on-rails - 如何在 Vagrant 中创建 Oracle 数据库并在我的本地 Rails 应用程序和 SQL Developer 中连接到它?
- python-3.x - 使用 asyncio 同时运行的两个协程
- git - Google repo 可以报告当前分支领先于远程吗?