【发布时间】:2018-05-28 14:44:31
【问题描述】:
我的项目是用递归的方式统计一个char数组的字数。
//Code:
public static int countWords(char[] array) {
if (array == null)
throw new IllegalArgumentException("The received array is null");
char[] array_new = trimLeadingSpaces(array);
//Arrays.copyOfRange(array_new, idxFirstSpace(array_new, 0), array_new.length);
if(idxFirstSpace(array_new, 0) == 0)
return 0;
if(idxFirstSpace(array_new, 0) == array_new.length)
return 1;
return 0;
}
}
我以前有两种方法来获取 char[] 中的第一个空格:trimLeadingSpaces(char[] array)(返回一个 char[];例如,我们有一个类似 [abc] 的 char[],它返回 [abc ]) 和另一个函数知道第一个 ' ' 的第一个索引:idxFirstSpace(char[] array, int currentIdx) 并返回一个 int。 我的问题出在 countWords() 方法中。
// test method coundWords
test_coundWords("abc"); // = 1
test_coundWords(" abc "); // = 1
test_coundWords(" abc def"); // = 2
test_coundWords(" abc def d"); // = 3
test_coundWords("a a def d g "); // = 5
test_coundWords(" "); // = 0
test_coundWords(""); // = 0
test_coundWords(null); // = Erro: The received array is null
控制台:
coundWords (abc) = 1
coundWords ( abc ) = 2 //HERE IS THE PROBLEM
coundWords ( abc def) = 2
coundWords ( abc def d) = 3
coundWords (a a def d g ) = 5
coundWords ( ) = 0
coundWords () = 0
coundWords (null) = Erro: The received array is null
我无法更改方法并将 char[] 更改为字符串。它必须只适用于 char 数组。
【问题讨论】:
-
如果你尝试拆分你的 char 数组怎么办?
-
无法将char数组改成字符串
-
那么对于
" abc ",我是否正确理解您的代码返回2 而不是1?如果是这样,您是否调试过您的代码,尤其是当trimLeadingSpaces()返回一个空数组或idxFirstSpace()返回数组中没有空间时会发生什么? -
尝试实现类似
trimLeadingSpaces(array);的方法,但去掉结尾空格 -
我也不能这样做@vincrichaud