2015-11-18 101 views
0

给定一个字符串数组,返回该数组,其中所有字符串的长度均为偶数,并替换为空字符串。给定一个字符串数组,将所有字符串的长度均替换为空字符串

blankAllEvens({ "Hi", "there", "bob" }) => {"", "there", "bob"} 
blankAllEvens({ "this", "is", "sparta!"}) => {"", "", "sparta!"} 
blankAllEvens({ }) => {} 

如何返回字符串? 我需要返回字符串以便为平铺打印空白空间,但现在我只是返回一个计数。 这是我的代码我认为一切正常,我只是不知道如何返回它?

public String[] blankAllEvens(String[] words) { 
int cnt = 0; 
    for (int i=0; i<words.length; i++) { 
    if (words[i].substring(0, 1).equals("2")) { 
    cnt++; 
    } 
    } 
    return cnt; 
} 
+0

我敢肯定'cnt'代表count,但那不是我怎么读的:) –

回答

2

在这里你去:

public String[] blankAllEvens(String[] words) { 
    for (int i=0; i <words.length; i++) { 
     if (words[i].length() % 2 == 0) { 
     words[i] = ""; 
     } 
    } 
    return words; 
} 

基本上,if语句检查是否在数组中的单词具有相同的平均长度(我们将字长2,看如果我们得到余数为0);在那种情况下,我们将其留空。

+0

我试过这个,现在说它找不到符号找不到符号 if(words [i] .length% 2 == 0){ ^ 符号:可变长度 位置:班级字符串 – stack101

+0

我已更新上述代码。 if语句应该是if(words [i] .length()%2 == 0){ – Kabir

相关问题