英文:
Convert a half width string in java to full width
问题
Sure, here is the translated content:
考虑一个半角字符串 'Hello'。我应该使用哪个 Java 库来获取其对应的全角字符串,即 'Hello'。
也欢迎提供任何示例代码。
英文:
Consider a half width string 'Hello'. What java library should I use to get its full width equivalent which is 'Hello'.
Any sample code is also appreciated.
答案1
得分: 2
半角和全角字符之间相差65248。所需做的只是将该数字简单地添加到每个字符。
使用流的示例:
public static String toFullWidth(String halfWidth) {
return halfWidth.chars()
.map(c -> c + 65248)
.collect(
StringBuilder::new,
(builder, c) -> builder.append((char) c),
StringBuilder::append
)
.toString();
}
使用循环的示例:
public static String toFullWidthWithLoop(String halfWidth) {
StringBuilder builder = new StringBuilder();
for (char c : halfWidth.toCharArray()) {
builder.append((char) (c + 65248));
}
return builder.toString();
}
英文:
Half and full width characters differ by 65248. So all you need to do is simply add that number to each character.
Example with stream:
public static String toFullWidth(String halfWidth) {
return halfWidth.chars()
.map(c -> c + 65248)
.collect(
StringBuilder::new,
(builder, c) -> builder.append((char) c),
StringBuilder::append
)
.toString();
}
Example with loop:
public static String toFullWidthWithLoop(String halfWidth) {
StringBuilder builder = new StringBuilder();
for (char c : halfWidth.toCharArray()) {
builder.append((char) (c + 65248));
}
return builder.toString();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论