Write a recursive, int-valued method, len, that accepts a string and returns the number of characters in the string.
The length of a string is:
0 if the string is the empty string ("").
1 more than the length of the rest of the string beyond the first character.

Respuesta :

Answer:

See Explanation Below

Explanation:

We name our recursive function to be "len" without the quotes

Also, the string whose length is to be calculated is named as StringCalc

Please note that only the function is written; the main method is omitted and it's written in Java Programming Language

The recursive function is as follows:

public int len(String StringCalc){

// Check if StringCalc is an empty string

if (StringCalc.isEmpty())

{

return 0;

}

// If otherwise; i.e. if StringCalc is not empty

else{

// Calculate length of string

int lengths = StringCalc.length();

// Return the length of string from the second character till the last

return (1 + len(StringCalc.substring(1, lengths)));

}

}

// End

The first line of the code declares the recursive function

public int len(String StringCalc)

The next line checks if the input string is empty

if (StringCalc.isEmpty())

This can also be written as

if(StringCalc == "")

If the above is true, the recursive returns the value of 0

Else; (i.e. if it's not an empty string), it does the following

It calculates the length of the string as follows

int lengths = StringCalc.length();

The length of the string is saved in variable "lengths"

Then the length of the string starting from the second character is calculated; since the index string is taken as 0, the recursive consider character at index 1 till the last index.

RELAXING NOICE
Relax