Java判斷一個字符串中包含另一字符串


1、contains方法

1、描述
java.lang.String.contains() 方法返回true,當且僅當此字符串包含指定的char值序列

2、聲明
public boolean contains(CharSequence s)  

3、返回值
如果此字符串包含,此方法返回true,否則返回false。

4、案例
public static void main(String[] args) {  
        String str = "abc";  
        boolean status = str.contains("a");  
        if(status){  
            System.out.println("包含");  
        }else{  
            System.out.println("不包含");  
        }  
    }  

2、indexOf方法

1、描述
java.lang.String.indexOf() 的用途是在一個字符串中尋找一個字的位置,同時也可以判斷一個字符串中是否包含某個字符。

2、聲明
int indexOf(int ch,int fromIndex)  

3、返回值
indexOf的返回值為int

4、案例
public static void main(String[] args) {  
    String str1 = "abcdefg";  
    int result1 = str1.indexOf("a");  
    if(result1 != -1){  
        System.out.println("字符串str中包含子串“a”"+result1);  
    }else{  
        System.out.println("字符串str中不包含子串“a”"+result1);  
    }  
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM