6

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)

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Ignacio, so does that mean, we can never know if a string is terminated except if(i == str.length()-1)??
@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.
Thanks Thilo!, I got your point, I was just wandering if writing such function is Java is possible at all
3

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));
    }

2 Comments

+1, this was the (completely contrived) example I would have written, had you not saved me from the task :)
@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++; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.