I'm trying to fully understand how the method works, see the code below:
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
I've debugged the method using BlueJ. The line:
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
firstly checks if the character at the index zero is a white space, then it calls itself again (this makes it recursive) taking the substring of s starting at index 1 as an argument effectively changing the argument from "a number of spaces " to " number of spaces " and doing it till the argument's length() reaches 0. What I don't get is why it's not returning 01000000100100000010 (the last 0 being for the empty string s which terminates the loop) but 4? I can't see where in the code it sums up the 1's returned by
(s.charAt(0) == ' ' ? 1 : 0)
and ignoring the 0's. Please advise me what is missing from my reasoning.
Many Thanks
Grzegorz(Greg)
If size of string str2 is greater then string str1 or size of string str1 is 0 then, return 0. Otherwise, Check if string str2 is present in str1 as substring or not. if present then, increment the count of occurrence and recursively call for other substring. else, recursively call for other substring.
To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the string.
Since the method returns an int, not a string, it adds the numbers, not concatenates as characters/strings. ie
0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
not
"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"
== "01000000100100000010"
below returns an int, since countspaces returns an int
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With