java - 返回所有满足条件的字符串值
问题描述
不知道如何设置这个方法,它获取一个字符串数组作为参数,并且必须在一个新数组中返回满足以下条件的所有值:数组的每个元素中 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++){
}
}
}
我有一个想法,它应该是这样的,但不能格式化代码来测试条件......
解决方案
您只需替换每个元素中的所有非数字,然后像这样比较长度:
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);
}
推荐阅读
- xamarin - 如何在 Xamarin.Forms 项目中调用 Xamarin.Droid 中定义的函数?
- r - 对具有相同值的数据进行排名
- heroku - 使用通配符将域指向 Heroku 应用程序
- scala - 参数 message.send.max.retries 在 kafka 生产者中不起作用
- esb - 企业服务总线 (ESB) 是用于创建服务还是仅用于配置/集成现有服务和应用程序?
- tfs - 是否可以使用 TFS 数据按计划自动生成报告?
- video-streaming - 使用 4g 连接的 HTTP 流式传输
- python-3.x - spark 2.3.1 上的 dataframe,Describe() 函数抛出 Py4JJavaError
- r - 用缺失数据填充行
- java - 来自 ok Retrofit 响应的空图像模型