Linux 拨号vps windows公众号手机端

android怎么判断字符串是否相等

lewis 9年前 (2016-12-07) 阅读数 6 #程序编程
文章标签 android

在Android中,判断两个字符串是否相等可以使用equals()方法或者equalsIgnoreCase()方法。

  1. 使用equals()方法:该方法用于比较两个字符串是否相等,严格区分大小写。
String str1 = "hello";
String str2 = "world";

if(str1.equals(str2)){
    // 字符串相等
}else{
    // 字符串不相等
}
  1. 使用equalsIgnoreCase()方法:该方法用于比较两个字符串是否相等,忽略大小写。
String str1 = "Hello";
String str2 = "hello";

if(str1.equalsIgnoreCase(str2)){
    // 字符串相等
}else{
    // 字符串不相等
}

需要注意的是,对于空字符串或者null值的比较,最好先进行判空处理,以避免出现空指针异常。

String str1 = "hello";
String str2 = null;

if(str1 != null && str1.equals(str2)){
    // 字符串相等
}else{
    // 字符串不相等
}
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门