java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java判断字符串

Java判断字符串为空、字符串是否为数字

投稿:junjie

这篇文章主要介绍了Java判断字符串为空、字符串是否为数字,其中数字的判断介绍了3种方法,需要的朋友可以参考下

关于 String 的判空:

复制代码 代码如下:
//这是对的
if (selection != null && !selection.equals("")) {
      whereClause += selection;
  }

//这是错的
if (!selection.equals("") && selection != null) {
      whereClause += selection;
  }

注:“==”比较两个变量本身的值,即两个对象在内存中的首地址。而“equals()”比较字符串中所包含的内容是否相同。第二种写法中,一旦 selection 真的为 null,则在执行 equals 方法的时候会直接报空指针异常导致不再继续执行。

判断字符串是否为数字:

复制代码 代码如下:

// 调用java自带的函数
public static boolean isNumeric(String number) {
  for (int i = number.length(); --i >= 0;) {
      if (!Character.isDigit(number.charAt(i))) {
          return false;
      }
  }
  return true;
}

// 使用正则表达式
public static boolean isNumeric(String number) {
  Pattern pattern = Pattern.compile("[0-9]*");
  return pattern.matcher(str).matches();
}

// 利用ASCII码

public static boolean isNumeric(String number) {
  for (int i = str.length(); --i >= 0;) {
      int chr = str.charAt(i);
      if (chr < 48 || chr > 57)
          return false;
  }
  return true;
}

您可能感兴趣的文章:
阅读全文