Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does recursive method to count white spaces in a string work?

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)

like image 559
user3274207 Avatar asked May 26 '14 11:05

user3274207


People also ask

How do you count something in recursion?

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.

How do you calculate spaces of a string?

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.


1 Answers

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));
like image 160
Viktor Mellgren Avatar answered Oct 13 '22 09:10

Viktor Mellgren