Skip to study material
← Question index

QUESTION 44 · String Operations

Write a function to find a string’s length without strlen.

5 marks

Answer in brief

A manual length function scans from the first character until the terminating null character is reached.

Algorithm

  1. Set length to zero.
  2. While s[length] is not the null character, increment length.
  3. Return length.

Worked trace

For "Code", index 0 contains C, index 1 contains o, index 2 contains d and index 3 contains e. Each adds one to length. At index 4 the null character is found, so the returned length is 4.

Return type

size_t is suitable for an object or string size. The sample obtains its declaration through stddef.h and prints it with %zu. It does not assume every valid string length fits int.

Precondition

The pointer must identify a valid string with a terminator reachable inside its permitted object. Without that terminator, the loop could read out of bounds; using a pointer or a library function does not repair an invalid string. A null pointer is not an empty string and cannot be passed here.

Boundary and text cases

An empty string starts with the terminator, so the loop runs zero times and returns zero. Spaces are counted like other non-null bytes. A multibyte encoded character may occupy several bytes, so this result is a byte-string length rather than a universal displayed-character count.

Complexity

For n non-null bytes, the loop makes n increments and a final stopping test. Time is O(n). It stores only the counter and pointer parameter, giving O(1) auxiliary space. The source is not modified or duplicated.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <stddef.h>
size_t text_length(const char *s)
{
    size_t length = 0;
    while (s[length] != '\0') { ++length; }
    return length;
}

int main(void)
{
    printf("Length = %zu\n", text_length("Code"));
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Length = 4

Related exam questions

Related questions in the string functions category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q7(b) · 8 marks

    Describe string library functions with syntax and an example program.

    Paper P01 · page 1
  • March/April 2023 · Q4(a) · 5 marks

    Explain strcat and strcpy with examples.

    Paper P02 · page 1

View this category in the exam question bank →