获取字符串以接受字符串[]作为参数?

时间:2015-10-28 18:36:23

标签: java arrays string methods

我目前正在尝试创建一种方法,将单词转换为复数形式。在这样做时,我有一些使用.endsWith()方法的级联if。

我有一个辅音字符串数组(+ y),我想用它作为endsWith()方法的参数。但它说我需要将类型consonant和Y方法更改为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"};

}

4 个答案:

答案 0 :(得分:2)

您可以使用正则表达式,而不是循环遍历consonantAndY,在该数组的每个元素上调用endsWith

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

答案 1 :(得分:1)

迭代数组

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

但更好的是上面用java 8

的答案

答案 2 :(得分:0)

使用java 8,你可以做到

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

// do something

}

Demo

答案 3 :(得分:0)

可以创建一个名为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;
}