String Length

How to find the string length without using loop and library function in c?

Keep string as struct and keep length with the string.

For ex:

struct string {
  int len;
  char str[1];
};

Later you can use something like

len = 8;
struct string *s = malloc( sizeof(string) + len ); /* 1 byte for '\0' */
if(s) {
  s->len = len;
  strcpy(s->str, "codechef");
}

And then len function would be simple

/* #define const */
int getlen(const struct string *s)
{
  return s->len; /* Neither loop, nor library */
}

Not quite sure, if this is what you wanted - using recursion instead of loop…

2 Likes

any idea without using stack method ?

where the len value (8) came from ?

@betlista 8 is the length of codechef string. If char codechef[] = “codechef”, 8 is actuall (int)sizeof codechef - 1. I picked this method from comp.lang.c FAQ list Question 2.6.

This is a solution good to demonstrate a trick but not useful. Technically it uses implicit stack and thus a hidden loop. Moreover this would be inefficient. Using strlen would be better in a real situation.

And you downvoted my answer because of that? The question was not to use library function or loop - this is what this puzzle was about…

exactly, 8 is hardcoded value in a code you want to find out, please implement the

int len(char* s)

method and show me the usage (without the loop or library function)…

I modified the code to enable possibility of len(s) calls and added number of test cases to input also…

@betlista OK ok, you win. I can not implement this method with the given contraints in the question. I tried but I could not.

@amitcom If you want the length of string literal, use sizeof. For depleted pointers, this is the only method I can think of. (Something similar is used by many stl containers also)

You can write a recursive function in C to find the length of string

void lengthofString(int n, char *string) {
    if(string[n] == '\0') {
        return;
    }
    lengthofString(n+1,string);
}