java判斷字符串是否包含某個字符(串)

個人博客 http://peoplevip.cnhtml

本篇地址 java

http://blog.peoplevip.cn/2018/b3681148.html#more測試

判斷一個字符串是否包含某個子串的n種方法spa

  • startsWith()
  • contains方法
  • indexOf方法

startsWith()

這個方法有兩個變體並測試若是一個字符串開頭的指定索引指定的前綴或在默認狀況下從字符串開始位置code

此方法定義的語法以下:htm

public boolean startsWith(String prefix, int toffset)
or
public boolean startsWith(String prefix)

prefix – 要匹配的前綴。這裏是參數的細節:blog

  • toffset – 從哪裏開始尋找字符串。

返回值爲true和false索引

import java.io.*;

public class Test{
   public static void main(String args[]){
      String Str = new String("Welcome to Yiibai.com");

      System.out.print("Return Value :" );
      System.out.println(Str.startsWith("Welcome") );

      System.out.print("Return Value :" );
      System.out.println(Str.startsWith("Tutorials") );

      System.out.print("Return Value :" );
      System.out.println(Str.startsWith("Yiibai", 11) );
   }
}

contains方法

java.lang.String.contains()ip

方法返回true,當且僅當此字符串包含指定的char值序列字符串

返回值爲true和false

public static void main(String[] args) {

        String str = "abc";

        boolean status = str.contains("a");

        if(status){
            System.out.println("包含");

        }else{
            System.out.println("不包含");
        }

    }

indexOf方法

java.lang.String.indexOf() 的用途是在一個字符串中尋找一個字的位置,同時也能夠判斷一個字符串中是否包含某個字符

indexOf的返回值爲int

public static void main(String[] args) {
    String str1 = "abcdefg";
    int result1 = str1.indexOf("ab");
    if(result1 != -1){
        System.out.println("字符串str中包含子串「ab」"+result1);
    }else{
        System.out.println("字符串str中不包含子串「ab」"+result1);
    }
}
相關文章
相關標籤/搜索