Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how string terminates in java?

Tags:

java

string

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)
like image 746
daydreamer Avatar asked Oct 20 '10 02:10

daydreamer


2 Answers

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

like image 101
Ignacio Vazquez-Abrams Avatar answered Sep 17 '22 22:09

Ignacio Vazquez-Abrams


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));
    }
like image 40
Upul Bandara Avatar answered Sep 17 '22 22:09

Upul Bandara