java語言程序設計 **10.25 第十章練習題 string類中split函數實現


**10.25(新的字符串split方法)String類中的split方法會返回一個字符串數組,該數組是由分隔符分開的字串構成的。但是,這個分隔符是不返回的。實現下面的新方法,方法返回字符串數組,這個數組由匹配字符分隔開的字串構成,字串也包括匹配字符。

public static String[] split(String s,String regex)

例如,split("ab#12#453","#")會返回ab、#、12、#和453構成的String數組,而split("a?b?gf#e","[?#]")會返回a、?、b、?、gf、#和e構成的字符串數組。

//package example4;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class ex5 {

    public static String[] split(String s,String regex) {
        ArrayList<String> matchList = new ArrayList<String>();
        Pattern pat = Pattern.compile(regex);  
        Matcher mat = pat.matcher(s);
        int index = 0;
        while(mat.find()) {
                String match = s.subSequence(index, mat.start()).toString();
                matchList.add(match);
                String match2 = s.subSequence(mat.start(),mat.end()).toString();
                matchList.add(match2);
                index = mat.end();
        }
        String match = s.subSequence(index,s.length()).toString();
        matchList.add(match);
        
        int resultSize = matchList.size();
        while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
            resultSize--;
        String[] result = new String[resultSize];
        return matchList.subList(0, resultSize).toArray(result);
        }
    public static void main(String[] args) {
        String[] ans=split("ab#123#453","#");
        System.out.println("模式串為“ab#123#453”,匹配串為“#”的匹配結果string數組為:");
        for(int i=0;i<ans.length;i++) {
            System.out.println(ans[i]);
        }
        String[] ans2=split("a?b?gf#e","[?#]");
        System.out.println("模式串為“a?b?gf#e”,匹配串為“[?#]”的匹配結果string數組為:");
        for(int i=0;i<ans2.length;i++) {
            System.out.println(ans2[i]);
        }
    }
    
}

 


免責聲明!

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



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