Open In App

C Program to Find the Length of a String

Last Updated : 05 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The length of a string is the number of characters in it without including the null character (‘\0’). In this article, we will learn how to find the length of a string in C.

The easiest way to find the string length is by using strlen() function from the C strings library. Let’s take a look at an example:

#include <stdio.h>
#include <string.h>

int main() {
    char s[] = "Geeks";

    // Find length of string using strlen()
    printf("%lu", strlen(s));
  
    return 0;
}

Output
5

There are also a few other methods in C to find the length of a string. They are as follows:

Using a Loop

Traverse the string using a loop from the first character till the null terminator (‘\0’) is encountered while counting the number of characters.

#include <stdio.h>

int findLen(char *s) {
    int c = 0;

    // Traverse string until null terminator
      // is found while incrementing counter
    while (*s++)
        c++;

    return c;
}

int main() {
    char s[] = "Geeks";

      // Find the length of s
    printf("%d", findLen(s));
  
    return 0;
}

Output
5

Using Pointer Arithmetic

Increment the pointer to the string array (different from the pointer to the first element of the string), dereference it and subtract the pointer to the first character of the string.

#include <stdio.h>

int main() {
    char s[] = "Geeks";

    // Calculate the length of the string using
      // pointer arithmetic
    int l = *(&s + 1) - s - 1;

    printf("%d", l);
    return 0;
}

Output
5

Note: This method can only be used when the string is declared as character array and only inside the same scope as string is declared.

Using Pointer Subtraction

Use pointer subtraction to find the difference between the pointer to the first and last character of the string, calculating the length excluding the null terminator.

#include <stdio.h>

int findLen(char* s) {
      char* last = s;
  
    // Go to the last character
      while(*last++);
      
      // Return difference between last and s
      return last - s - 1;
}

int main() {
    char s[] = "Geeks";

    // Print the length of string s
    printf("%d", findLen(s));
    return 0;
}

Output
5


Next Article

Similar Reads

three90RightbarBannerImg