-2

EDIT: Really sorry, I mean Java! As for what I think, I would say the first contains if statement is for s == null or length 0, but I'm confused as to what to put in the

return spaceCount(s.substring(1, ......)) + ......;

part.

I'm trying to use some if statements to write a function that takes a string as a parameter and recursively coutns the number of blanks spaces " " it has. So far I have

public static int spaceCount (string s) {
    if ( ...... ) {
        return 0;
    }
    char c = s.charAt(0);
    if (....... ) {
        return spaceCount (.....);
    } else {
        return spaceCount(s.substring(1, ......)) + ......;
    }
}

So in the first if statement, should I write the case of the string having zero length? I'm pretty sure that won't cover the case of no spaces at all, so I'm not sure how to proceed.

For the second and third, I know I have to scan the string for spaces, but I am not really sure how to do that either. Any hints or direction would be appreciated!

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Anon Anon
  • 1
  • 1
  • 3
  • That's a lot of ellipses. Can you try filling some of those in? Or at least comments about what you think should go in them? – jxh May 07 '13 at 01:43
  • simple `.characterIsWhitespace` could work right? – Tdorno May 07 '13 at 01:51
  • Using recursion to count blanks in a string is not wise. It makes poor use of recursion. However, if I were doing it I'd have the recursive routine go deep first and then do the counting on return. – Hot Licks May 07 '13 at 02:09
  • I think it's fair to assume that this is a 'learning recursion' exercise. There are far more efficient ways of counting characters in a string, but few simple ways of learning how recursion works. – Jason May 13 '13 at 00:11

4 Answers4

3
public static int spaceCount(final String s) {

    if(s == null || s.length() == 0) {
        return 0;
    }

    char c = s.charAt(0);
    if(' ' != c) {
        return spaceCount(s.substring(1));
    } else {
        return spaceCount(s.substring(1)) + 1;
    }

}

You don't have to "scan the string for spaces", that's what the recursion passing the remainder of the string does.

Jason
  • 11,744
  • 3
  • 42
  • 46
  • In the else statement, do you mean return spaceCount(s.substring(1,...)) + 1; or...? Should I use (1, s.length)? Or i may have made a typo... – Anon Anon May 07 '13 at 02:37
  • The code in the else block needs to recurse into spaceCount passing the current string without the leading character, but it needs to return with the responding value + 1 because the first character at this point is a space. – Jason May 13 '13 at 00:03
  • Also, s.substring(1) would return the same thing as s.substring(1, s.length()) in this instance. – Jason May 13 '13 at 00:04
2
s.length() - s.replaceAll(" ", "").length() returns you number of spaces.

how to count the spaces in a java string? has the answer. Probably it may help. the above line is the simplest.

Community
  • 1
  • 1
Siva Tumma
  • 1,695
  • 12
  • 23
  • The OP mentioned "recursively". – Jason May 07 '13 at 01:50
  • That "recursive" thing sounds unnecessary... why should you go for a recursion here ? Do anyone have a justification ? – Siva Tumma May 07 '13 at 01:56
  • Yes - it's probably what the homework question asked. Either way, it's what the OP asked. – Jason May 07 '13 at 01:57
  • Your answer was correct but the method says that this person needs recursively as a main method but good try pal ! :D –  May 07 '13 at 02:36
0

[You didn't specify a programming language] Here is a solution in Java:

public static int spaceCount(String s)
{ return scRecursive (s, s.length, 0, 0); }

public static int scRecursive (String s, int len, int dex, int count)
{ if (len == dex) return count;
  else
    return scRecursive (s, len, dex + 1,
                        (' ' == s.charAt(dex) ? count + 1 : count)); }

This is tail recursive (which might imply some efficiency) and, more importantly, this does not copy/allocate substrings

Here is one in Scheme:

(define (space-count string)
  (let ((length (string-length string)))
    (let stepping ((index 0) (count 0)
      (if (= index length)
          count
          (let ((char (string-ref string index)))
            (stepping (+ index 1)
                      (if (equal? #\space char)
                          (+ 1 count)
                          count)))))))

The recursion is in the call to stepping which has two arguments - the current index and the current count of spaces. The recursion terminates when the index equals the length. The count is incremented when the current char is a space.

GoZoner
  • 67,920
  • 20
  • 95
  • 145
  • Given a recursive algorithm in language X it is trivial to put it in language Y. The OP needs to do some homework after all. – GoZoner May 07 '13 at 01:49
0
public class CountSpaces {

    public static void main(String[] args) {
        String str = "     A   ";
        System.out.println(spaceCount(str, 0));
        System.out.println(spaceCount(str));
    }

    public static int spaceCount(String str, int count) {
        if (str == null) {
            return 0;
        } else if (str.length() > 0) {
            char c = str.charAt(0);
            if (Character.isWhitespace(c)) {
                count++;
            }
            return spaceCount(str.substring(1), count);
        } else {
            return count;
        }
    }

    public static int spaceCount(String s) {
        if (s.length() == 0 || s == null) {
            return 0;
        }
        char c = s.charAt(0);
        if (!Character.isWhitespace(c)) {
            return spaceCount(s.substring(1));
        } else {
            return spaceCount(s.substring(1, s.length())) + 1;
        }
    }
}
Crazenezz
  • 3,416
  • 6
  • 31
  • 59
  • I understand that the first statement returns 0 for a null string, but is there any way for it to check that a string has no spaces? Also, it not possible to check for spaces in the format I've used or without whitespace? – Anon Anon May 07 '13 at 02:56
  • @AnonAnon: Please see the edited answer, I corrected as you ask in your question above. – Crazenezz May 07 '13 at 02:59
  • Thanks for answering. I guess I was trying to ask if actually using s.substring(1, s.length()) was correct, since I was just guessing? Sorry for the confusion. – Anon Anon May 07 '13 at 03:04
  • Than the answer is "Yes it can". There is many ways to complete your problem. Not just using `s.substring(1, s.length())` is the only correct answer. – Crazenezz May 07 '13 at 03:10