首页 > 解决方案 > 返回所有满足条件的字符串值

问题描述

不知道如何设置这个方法,它获取一个字符串数组作为参数,并且必须在一个新数组中返回满足以下条件的所有值:数组的每个元素中 25% 的字符是数字;

public static String[] returnSentence(String[] str){
    int nrOfWords = str.length;
    int count = 0;
    for(int i = 0; i < nrOfWords; i++){
        for(int j = 0; j < str[i].length; j++){

        }
    }
}

我有一个想法,它应该是这样的,但不能格式化代码来测试条件......

标签: javaarraysstring

解决方案


您只需替换每个元素中的所有非数字,然后像这样比较长度:

public static List<String> returnSentence(String[] str) {
    int nrOfWords = str.length;
    List<String> result = new ArrayList<>();
    for (int i = 0; i < nrOfWords; i++) {
        if(str[i].replaceAll("\\D", "").length() == str[i].length() * 0.25){
            result.add(str[i]);
        }
    }
    return result; // If you want an array use : return result.toArray(String[]::new);
}

作为结果,我也会使用 List 而不是数组,因为您不知道有多少元素符合条件。

如果你想用流媒体解决它可以更容易:

public static String[] returnSentence(String[] str) {
    return Arrays.stream(str)
            .filter(s-> s.replaceAll("\\D", "").length() == s.length() * 0.25)
            .toArray(String[]::new);
}

推荐阅读