繁体   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