将 Java 中的半角字符串转换为全角。

huangapple go评论146阅读模式
英文:

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();
}

huangapple
  • 本文由 发表于 2020年9月16日 00:09:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63905865.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定