by Sai gowtham

How to find the length of a given string in C

In this tutorial, we are going to learn about two different ways to find the length of a string in C.

Using the str_len() function

The built-in str_len() function helps us to find the length of a given string that is defined inside the string.h header file.

The str_len() function takes the string as an argument and returns its length.

Example:

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

int main() {
  char user[10] = "Gowtham";
  int length = strlen(user);
  printf("User length: %u", length);
}

Finding the length manually using for loop and while loop

We can also find the length of a string without using the str_len() function, by manually looping through the each character in a string and store the count value in a variable.

For loop:

#include <stdio.h>

int main() {
    char user[10] = "Gowtham";
    int i = 0;
    for (i; user[i] != '\0'; i++);    printf("User length: %d", i);
    return 0;
}

While loop:

#include <stdio.h>

int main() {
    char user[10] = "Gowtham";
    int i = 0;
    while (user[i] != '\0'){      i++;    }    printf("User length: %d", i);
    return 0;
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course