JAVA中如何处理中文的全角和半角问题- -

/**
*  把给定的中文字符串转化为定宽字符串,若源串长则裁掉,若不足则在尾端补足。
*  保证转化后的字符串只包含中文全角字符。
*/
public static String fixedWidthStringDBCS(String str, int width, char fill) {
    if (str==null) str = "";
    if (fill < 256) fill = ' ';
    StringBuffer sb = new StringBuffer();

    int i=0;
    for ( ; i<str.length() && i<width; i++) {
        int c = str.charAt(i);
        if (c >= 'a' && c<='z') { //azAZ 019
            c = c + 'a' - 'a';
        } else if (c >= 'A' && c<= 'Z') {
            c = c + 'A' - 'A';
        } else if (c >= '0' && c<= '9') {
            c = c + '0' - '0';
        } else if (c < 256) {
            c = fill;
        }

        sb.append((char)c);
    }

    for ( ; i<width; i++) {
        sb.append(fill);
    }

    return sb.toString();
}

 

我改写的一个简便功能的方法:

 public String fixedWidthStringDBCS(String str) {
  if (str==null) str = "";
  int width = str.length();
  StringBuffer sb = new StringBuffer();

  int i=0;
  for ( ; i<str.length() && i<width; i++) {
   int c = str.charAt(i);
   if (c >= 'a' && c<='z') { //azAZ 019
    c = c + 'a' - 'a';
   } else if (c >= 'A' && c<= 'Z') {
    c = c + 'A' - 'A';
   } else if (c >= '0' && c<= '9') {
    c = c + '0' - '0';
   }

   sb.append((char)c);

  }


  return sb.toString();
 }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java正则表达式如何匹配全角/半角空格: Java正则表达式是一种强大的工具,用于在字符串进行模式匹配。要匹配全角/半角空格,我们可以使用Unicode字符范围来实现。 在Unicode字符范围全角空格的编码是U+3000,而半角空格的编码是U+0020。根据这些编码,我们可以使用Java正则表达式来匹配全角/半角空格。 假设我们有一个字符串str,并且我们想要匹配其全角/半角空格,我们可以使用以下正则表达式来实现: 全角空格:\u3000 半角空格:\u0020 例如,我们可以使用以下代码段来匹配字符串全角/半角空格并统计其个数: ```java import java.util.regex.*; public class Main { public static void main(String[] args) { String str = "你好, Java!"; //含有全角空格、半角空格 int count = 0; Pattern pattern = Pattern.compile("[\u3000\u0020]"); //匹配全角/半角空格 Matcher matcher = pattern.matcher(str); while (matcher.find()) { count++; } System.out.println("全角/半角空格个数:" + count); } } ``` 在上面的代码,我们使用Pattern.compile("[\u3000\u0020]")来创建一个正则表达式,用于匹配全角/半角空格。然后,我们使用Matcher的find()方法在字符串查找匹配项,并使用一个计数器记录匹配到的次数。最后,我们输出匹配到的全角/半角空格的个数。 以上就是使用Java正则表达式匹配全角/半角空格的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值