簡體   English   中英

返回所有符合條件的字符串值

[英]returning all string values that meet the condition

不確定如何設置此方法,該方法將String數組作為參數,並且必須在新數組中返回滿足以下條件的所有值:每個數組元素中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而不是array,因為您不知道有多少元素符合條件。

如果您想使用流媒體解決,則可以更輕松:

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

您的問題基本上可以歸結為弄清在給定條件下,字符串中有多少個字符,而沒有多少個字符。

有兩種方法可以做到這一點:

1)簡單地計算字符:

int numPositiveChars = 0;
int numNegativeChars = 0;
for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    if (/*check c here*/)
        numPositiveChars++;
    else
        numNegativeChars++;
}

實際上,您甚至不需要計算負數,因為該值只是s.length() - numPositiveChars

2)另一種方法是使用正則表達式,例如,通過刪除所有非數字字符然后獲取字符數:

int numPositiveChars = s.replaceAll("[^0-9]+", "").length();

此行將從字符串中刪除所有非數字字符(非0-9),然后返回結果的長度(數字字符數)。

一旦擁有符合條件的字符數,計算百分比就變得微不足道了。

像這樣的東西

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++){
    for(int j = 0;j<str[i].length;j++){
      if(Character.isAlphabetic(str[i].getcharat(j)))
   {
     count++;
   }
   if((count/100.0)*100>=25)
    {  temp_Str[k]=str[i];
       k++;
       }


    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM