當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Pattern splitAsStream()用法及代碼示例


Pattern類的splitAsStream()方法用於從給定的輸入序列返回作為此模式匹配周圍的參數傳遞的給定輸入序列的String流。此方法與split方法相同,隻是返回的不是String對象數組,而是流。如果此模式與輸入的任何子序列都不匹配,則結果流隻有一個元素,即字符串形式的輸入序列。

用法:

public Stream<String> splitAsStream(CharSequence input)

參數:此方法接受單個參數CharSequence,該參數表示要拆分的字符序列。


返回值:此方法返回通過在此模式的匹配項附近拆分輸入而計算出的字符串流。

以下示例程序旨在說明splitAsStream()方法:

示例1:

// Java program to demonstrate 
// Pattern.splitAsStream(CharSequence input) method 
  
import java.util.regex.*; 
import java.util.stream.*; 
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = "geeks"; 
  
        // create the string 
        // in which you want to search 
        String actualString 
            = "Welcome to geeks for geeks"; 
  
        // create a Pattern using REGEX 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // split the text 
        Stream<String> stream 
            = pattern 
                  .splitAsStream(actualString); 
  
        // print array 
        stream.forEach(System.out::println); 
    } 
}
輸出:
Welcome to 
 for

示例2:

// Java program to demonstrate 
// Pattern.splitAsStream(CharSequence input) method 
  
import java.util.regex.*; 
import java.util.stream.*; 
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = "ee"; 
  
        // create the string 
        // in which you want to search 
        String actualString 
            = "aaeebbeecceeddee"; 
  
        // create a Pattern using REGEX 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // split the text 
        Stream<String> stream 
            = pattern 
                  .splitAsStream(actualString); 
  
        // print array 
        stream.forEach(System.out::println); 
    } 
}
輸出:
aa
bb
cc
dd

參考: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#splitAsStream(java.lang.CharSequence)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Pattern splitAsStream() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。