Java如何迴圈數組並使用Split

來源:互聯網
上載者:User

標籤:方法   inf   regex   --   不能   lang   bsp   sys   ima   

情境: 當寫方法時遇到1個參數有3個值, 該參數類型為數組。    例如:  aaa|bbb|ccc  .  而且需要迴圈列印,這個時候我們就需要用數組迴圈輸出的方法。

 

一:feature 樣本

    When I click on menu 時間管理>休假結餘>休假結餘設立 from HCM page    And I advance search staff no 0006    Then I select leaveCode for NAL|SL2|OL|

 

二: steps 樣本:

 

@Then("^I select leaveCode for (.+)$")    public void i_select_leaveCode_for(String leaveCode) throws Throwable {        vp.selectLeaveCodeFor(leaveCode);    }

 

 

三:  Page 樣本:

     

 /**      * 休假結餘設立菜單,篩選多個休假類型。      * @param leaveCode     * @throws Exception       */     public void selectLeaveCodeFor(String leaveCode) throws Exception {         waitFor(By.xpath("//span[@id=‘divLeaveCodesShowWindow‘]")).click();         String[] array = leaveCode.split("\\|");             for (int i = 0; i < array.length; i++) {            String xpath = "//tr[./td[text()=‘"+ array[i] +"‘]]/td[1]/input";            waitFor(By.xpath(xpath)).click();        }         waitLoading();         waitFor(By.xpath("//input[@id=‘confirmdivLeaveCodesSelection‘][@value=‘確認‘]")).click();         waitFor(By.xpath("//a[@id=‘btnSearch‘]/i")).click();         waitLoading();     }

情境圖:

             

 

 

四:Split 常見使用方法

在java.lang包中有String.split()方法,返回是一個數組

我在應用中用到一些,給大家總結一下,僅供大家參考:

1、如果用“.”作為分隔的話,必須是如下寫法,String.split("\\."),這樣才能正確的分隔開,不能用String.split(".");

2、如果用“|”作為分隔的話,必須是如下寫法,String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|");

“.”和“|”都是逸出字元,必須得加"\\";

3、如果在一個字串中有多個分隔字元,可以用“|”作為連字號,比如,“acount=? and uu =? or n=?”,把三個都分隔出來,可以用String.split("and|or");

使用String.split方法分隔字串時,分隔字元如果用到一些特殊字元,可能會得不到我們預期的結果。 

我們看jdk doc中說明  

public String[] split(String regex)

 Splits this string around matches of the given regular expression. 

參數regex是一個 regular-expression的匹配模式而不是一個簡單的String,他對一些特殊的字元可能會出現你預想不到的結果,比如測試下面的代碼用豎線 | 分隔字串,你將得不到預期的結果

 

例如情況A: aaa|bbb|ccc

    String[] aa = "aaa|bbb|ccc".split("\\|"); 這樣才能得到正確的結果    for (int i = 0 ; i <aa.length ; i++ ) {      System.out.println("--"+aa[i]);     } 

 

 

例如B: aaa*bbb*ccc

    String[] aa = "aaa|bbb|ccc".split("\\*"); 這樣才能得到正確的結果        for (int i = 0 ; i <aa.length ; i++ ) {      System.out.println("--"+aa[i]);     }  

 

Java如何迴圈數組並使用Split

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.