tags:

views:

104

answers:

3

Hi
I am trying to write a recursive function which calculates the length of string in Java
I know that there already exists str.length() function, but the problem statement wants to implement a recursive function

In C programming language the termination character is '\0', I just want to know how to know if string ends in Java

My program ends well when I put '\n' in the test string. Please let me know. Thanks!

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package careercup.google;

/**
 *
 * @author learner
 */
public class Strlen {
    private static final String Test = "abcdefg\n";
    private static int i =0;

    public static void main(String args[]){
        System.out.println("len : " + strlen(Test));
    }

    private static int strlen(String str){
        if(str == null){
            return 0;
        }
        if(str.charAt(i) == '\n'){
            return 0;
        }
        i += 1;
        return 1 + strlen(str);
    }
}

Output :

run:
len : 7
BUILD SUCCESSFUL (total time: 0 seconds)
+8  A: 

Java strings are not C strings. The string ends after the number of characters in its length.

Ignacio Vazquez-Abrams
Hi Ignacio, so does that mean, we can never know if a string is terminated except if(i == str.length()-1)??
learner
@learner. Yes. But conversely, you can call String.length and it will tell you the length without having to iterate the whole string to find the terminator. This is a good thing.
Thilo
Thanks Thilo!, I got your point, I was just wandering if writing such function is Java is possible at all
learner
+2  A: 

Please keep in mind that this code is very inefficient, but it calculates length of a String in recursive way.

private static int stringLength(String string){
        if(string == null){
            return 0;
        }

        if(string.isEmpty()){
            return 0;
        }

        return 1 + stringLength(string.substring(1));
    }
Upul
+1, this was the (completely contrived) example I would have written, had you not saved me from the task :)
Merlyn Morgan-Graham
@learner: This example is a lot less contrived in C, where you have access to bare memory, and the code (when optimized) compiles down to the same loop as: `int count = 0; while (pointerToChar++ != NULL) { count++; }`
Merlyn Morgan-Graham
A: 

I don't think this is a good question, since String in Java is backed by a char array with a count, you can get the length very simply, why take the trouble to implement a recursive method?

lostinmoney
The question includes "the problem statement" and the poster mentionned `string.length` himself. I therefore assume this is some kind of exercise on recursive functions: recursive invocation + termination condition. The question, as how to express the termination condition given that there is no "sentinel" character is perfectly valid, IMHO.
André Caron