Pictured is a peer learning day occuring

 

STRLEN in C


How do you measure strings? With a ruler? I’m legitimately curious. In C, at least, you can do so using the function strlen.

PREFACE - WHAT IS C?

More than just the third letter of the alphabet, C is a compiled programming language - in other words, C is run by a computer only after being compiled. Compilation is accomplished by software called compilers, which take C source code files and translate them into executable language (binary) that computers can run.

There are many different C compilers, but in this tutorial, I will be using one called GCC, published by GNU. For instructions on how to install GCC, you can visit GNU’s installation guide here (https://gcc.gnu.org/install/).

Throughout the duration of this article, I exemplify usage of GCC on the command line. If you are unfamiliar with what a command line is, read more here (http://linuxcommand.org/index.php).

To read more on what C is and how to use it, read my earlier post on the topic (Learn C)

STRLEN - WHAT

The function strlen (think, "string length") is a C standard library function that returns the length of a string.

String length will not make much sense without a fundamental understanding of what strings in C are. Remember - strings are no more than arrays of ASCII-encoded characters ending with a terminating null byte (\0). A pointer to a string is merely a pointer to the first character in this array.

For example, when we create a string "Holberton", we truly create an array of ten ASCII characters 'H', 'o', 'l', 'b', 'e', 'r', 't', 'o', 'n', '\0'. In memory, this string can be represented like so:

char str1[10] = "Holberton";
Address 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
Variable str1
Value H o l b e r t o n \0

Now, the length of this string is 9.

Did you do a double-take? No, I did not misspeak (Or, miswrite? What’s the proper term for articles?) - while the string "Holberton" takes up ten bytes in memory, it’s length is not 10, but 9, corresponding directly to the number of non-null-byte characters.

Think about string length as word (or sentence) length, not size in memory.

PARAMETERS
const char *str

The function receives one parameter, a pointer to the string to measure the length of. Note that the string is received as a constant - the function strlen will never alter the received string.

RETURN VALUE
size_t

The function strlen returns a number, specifically, a size_t (an unsigned integer type designed to hold any array index), representing the length of the received string.

DECLARATION

The function strlen is declared as follows:

/**
* strlen - Returns the length of a string.
* @str: The string to get the length of.
*
* Return: The length of @str.
*/
size_t *strlen(const char *str)

STRLEN - HOW

To use the function strlen, include the C standard library using the header <string.h>.

#include <string.h>

Once the C string library has been included, you can call the function strlen directly.

Example (note that the libraries <stdio.h> and <stdlib.h> are additionally included here for the usage of printf and EXIT_SUCCESS, respectively):

$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char str[10] = "Holberton";
    size_t length;

    length = strlen(str);

    printf("The length of the string %s is %lu.\n", str, length);

    return (EXIT_SUCCESS);
}
$ gcc main.c -o strlen
$ ./strlen
The length of the string Holberton is 9.                                                                      

STRLEN - WHEN

String lengths are ubiquitous in C programs. Looping over strings? One way you could do so is iterating indices for the length of the string.

$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char str[10] = "Holberton";
    size_t length, index;

    length = strlen(str);
    for (index = 0; index < length; index++)
        printf("%c\n", str[index]);

    return (EXIT_SUCCESS);
}
$ gcc main.c -o loop
$ ./loop
H
o
l
b
e
r
t
o
n                        

Comparing strings? You’re most likely interested in comparing their lengths.

$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char *str1 = argv[1];
    char *str2 = argv[2];
    size_t length1, length2;

    length1 = strlen(str1);
    length2 = strlen(str2);
    
    if (length1 < length2)
        printf("str1 < str2\n");
    else if (length1 == length2)
        printf("str1 == str2\n");
    else
        printf("str1 > str2\n");

    return (EXIT_SUCCESS);
}
$ gcc main.c -o compare
$ ./compare Holberton School
str1 > str2                                           

One example where strlen becomes particularly useful, if not crucial, is when working with dynamically-allocated memory. In fact, you may recognize examples combining strlen and malloc from some of my other function tutorials. For example, my capitalization function from the article on strcpy:

$ cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    /* Get word to capitalize from command line */
    char *word = argv[1];

    /* Dynamically allocate temporary buffer */
    char *tmp = malloc(strlen(word) + 1);
    /* Return error if allocation failed */
    if (tmp == NULL)
        return (EXIT_FAILURE);

    /* Initialize tmp with null bytes for good practice */
    memset(tmp, '\0', strlen(word) + 1);

    printf("Before capitalization: %s\n", word);

    /* Copy word into tmp */
    strcpy(tmp, word);

    /*
        * If first character of word is lowercase letter, capitalize it.
        * Capitalized version of a lowercase letter is -ASCII value 32.
        */
    if (tmp[0] >= 'a' && tmp[0] <= 'z')
        tmp[0] -= 32;

    /* Reassign capitalized word */
    word = tmp;

    printf("After capitalization: %s\n", word);

    /* One free for each malloc */
    free(tmp);

    return (EXIT_SUCCESS);
}
$ gcc main.c -o dynamic
$ ./dynamic brennan
Before capitalization: brennan
After capitalization: Brennan

In the above, strlen helps me allocate just the space I need to create a copy of the string to capitalize - no more, no less.

Dare I say - strlen will be your most used string function in C.

ADVANCED 100 - IMPLEMENTATION

The function is ubiquitous, but I think you’ll find its logic familiar. I present, my implementation of the function strlen.

/*
* File: 2-strlen.c
* Auth: Brennan D Baraban
*/

#include "holberton.h"

/**
* _strlen - Returns the length of a string.
* @str: The string to get the length of.
*
* Return: The length of @str.
*/
size_t _strlen(const char *str)
{
    size_t length = 0;

    while (*str++)
        length++;

    return (length);
}

source: https://github.com/bdbaraban/holbertonschool-low_level_programming/blob/master/0x04-pointers_arrays_strings/2-strlen.c

To get the length of a string, I rely on finding the terminating null byte. I loop over the received string, iterating a count for each character until I hit the null byte. At that point, I have reached the end of the string, and have measured its entire length!

Of course, this is just one, personal implementation of the function strlen. There are multiple ways to do so; in fact, I encourage, no, challenge, you to find another way to write this function!

NOTE

Examples in this article were compiled and run on a Linux Ubuntu 18.04 LTS machine with GNU GCC version 7.3.0.
Written by:

Brennan Baraban, Cohort 7 (SF Campus)