猿问

返回满足条件的所有字符串值

不知道如何设置此方法,该方法获取字符串数组作为参数,并且必须在新数组中返回满足以下条件的所有值:数组的每个元素中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++){


        }

    }

}

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


白衣非少年
浏览 151回答 3
3回答

慕的地10843

你的问题基本上可以归结为弄清楚字符串中有多少个字符完整地填充了给定的条件,有多少字符没有。有两种方法可以做到这一点:1)简单地计算字符:int numPositiveChars = 0;int numNegativeChars = 0;for (int i = 0; i < s.length(); i++){&nbsp; &nbsp; char c = s.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (/*check c here*/)&nbsp; &nbsp; &nbsp; &nbsp; numPositiveChars++;&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; numNegativeChars++;}实际上,您甚至不需要计算负字符,因为该值只是。s.length() - numPositiveChars2)另一种方法是使用正则表达式,例如通过删除所有非数字字符,然后获取字符计数:int numPositiveChars = s.replaceAll("[^0-9]+", "").length();此行将从 String 中删除所有非数字字符(不是 0-9),然后返回结果的长度(数字字符数)。一旦你有了符合你条件的字符数,计算百分比就变得微不足道了。

MMTTMM

您只需要替换每个元素中的所有非数字,然后像这样比较长度:public static List<String> returnSentence(String[] str) {&nbsp; &nbsp; int nrOfWords = str.length;&nbsp; &nbsp; List<String> result = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i < nrOfWords; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(str[i].replaceAll("\\D", "").length() == str[i].length() * 0.25){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(str[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result; // If you want an array use : return result.toArray(String[]::new);}我也会使用List而不是数组作为结果,因为你不知道有多少元素是尊重条件的。如果你想用流媒体解决,它可以更容易:public static String[] returnSentence(String[] str) {&nbsp; &nbsp; return Arrays.stream(str)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(s-> s.replaceAll("\\D", "").length() == s.length() * 0.25)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(String[]::new);}

一只甜甜圈

像这样的东西public static String[] returnSentence(String[] str){int nrOfWords= str.length;String[] temp_Str = new String[20];int count = 0;int k=0;for(int i = 0;i<nrOfWords;i++){&nbsp; &nbsp; for(int j = 0;j<str[i].length;j++){&nbsp; &nbsp; &nbsp; if(Character.isAlphabetic(str[i].getcharat(j)))&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp;count++;&nbsp; &nbsp;}&nbsp; &nbsp;if((count/100.0)*100>=25)&nbsp; &nbsp; {&nbsp; temp_Str[k]=str[i];&nbsp; &nbsp; &nbsp; &nbsp;k++;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}}
随时随地看视频慕课网APP

相关分类

Java
我要回答