Write a recursive, int -valued function, len, that accepts a string and returns
ID: 3548083 • Letter: W
Question
Write a recursive, int -valued function, 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 .
Answer I've tried:
public class Random
{
public static int len(String s)
{
if(s.equals(""))
return 0;
else
return 1 + len(s.substring(0, s.length()-1));
}
public static void main(String args[])
{
System.out.println(len("asdf"));
}
}
Compiler error messages:
? You almost certainly should be using: ==
? You almost certainly should be using: string
? I haven't yet seen a correct solution that uses: [ ]'
Explanation / Answer
#include <iostream>using namespace std;
size_t slength( const char s[] )
{
return ( *s == '' ? 0 : 1 + slength( s + 1 ) );
}
int main() {
int i; i=slength("asdf");
cout<< i; return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.