搜尋
首頁JavaJava基礎java中判斷字串中是否包含某個特定字串的方法有哪些

java中判斷字串中是否包含某個特定字串的方法有哪些

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

#1、startsWith()方法

2、contains()方法

3、indexOf方法

startsWith()方法


##這個方法有兩個變體,用於檢測字串是否以指定的前綴開始。

此方法定義的語法如下:

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

參數說明:

#prefix – 要符合的前綴。 toffset

– 從哪裡開始尋找字串。

返回值:

true和false

相關影片教學推薦:

java學習影片

#範例:

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()

方法傳回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()
###用途是在一個字串中尋找一個字的位置,同時也可以判斷一個字串中是否包含某個字元。 #########返回值:######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);
    }
}
###更多相關教學請造訪:###java入門學習## ####

以上是java中判斷字串中是否包含某個特定字串的方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版