簡體   English   中英

獲取字符串以接受string []作為參數?

[英]Getting a string to accept a string[] as a param?

我目前正在嘗試創建一種將單詞轉換為復數形式的方法。 在執行此操作時,我使用.endsWith()方法進行了級聯if。

我有一個輔音(+ y)字符串數組,我想將其用作endsWith()方法的參數。 但是它說我需要將類型consonantandY方法更改為String而不是String []。 如果這樣做,我將無法建立數組...

我該如何解決?

    private String regularPluralForm(String word) {
    String s2 = "";
    if(word.endsWith("s)")) {
        s2 = "es";
    } else if(word.endsWith("x)")) {
        s2 = "es";
    } else if(word.endsWith("z")) {
        s2 = "es";
    } else if(word.endsWith("ch")) {
        s2 = "es";
    } else if(word.endsWith("sh"))  {
        s2 = "es";
    } else if(word.endsWith(consonantAndY)) {

    }
    String correctWord = word+s2;
    return correctWord;

}
private static final String[] consonantAndY = {"by","cy","dy","fy",
                                             "gy","hy","jy","ky"
                                             ,"ly","my","ny"
                                             ,"py","qy","ry","sy"
                                             ,"ty","vy","wy","xy"
                                             ,"yy","zy"};

}

您可以使用正則表達式,而不是遍歷consonantAndY ,在該數組的每個元素上調用endsWith

} else if (word.matches(".*[bcdfghjklmnpqrstvwxyz]y")) {

遍歷數組

else {
  boolean matches = false;
  for(String s : constantAndY) {
   if (word.endsWith(s)) {
      matches = true;
      break;
   }
}

但更好的顯然是上述與Java 8的答案

使用Java 8,您可以執行

if( Arrays.asList(consonantAndY).stream().anyMatch(t -> word.endsWith(t)) ){

// do something

}

演示版

可以創建一個名為endsWith的輔助方法,該方法將數組作為參數。

int consonantIndex = -1;
if (...) { ... }
else if((consonantIndex = endsWith(word, consonantAndY)) != -1) {
    s2 = consonantAndY[consonantIndex];
}

private int endsWith(String s, String... suffixes) {
    for (int i = 0; i < suffixes.length; i++) {
        if (s.endsWith(suffixes[i])) {
            return i;
        }
    }
    return -1;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM