简体   繁体   中英

Convert a half width string in java to full width

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.

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

Try this :

    String s = "Hello" ;
    System.out.println(s.replaceAll(""," ")) ;

you will get H ello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM