The Wayback Machine - https://web.archive.org/web/20240904162533/https://www.geeksforgeeks.org/c-program-to-find-the-length-of-a-string/
Open In App

C Program to Find the Length of a String

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
46.75%
13.4K

Write a C program to find the length of a string.

The length of a string is the number of characters in it excluding the null character (‘\0’).

Examples:

Input: str[] = “Hello”
Output: 5
Explanation: The string “Hello” has 5 characters.

Input: str[] = “GeeksforGeeks”
Output: 13
Explanation: The string “GeeksforGeeks” has 13 characters.

Different Ways to Find the Length of a String in C

There can be many different ways to find the length of the string. Some of the popular methods are listed below:

1. Find the Length of the String Using a Loop

The idea is to initializes a variable length to zero. Then iterates through the string character by character, checking each character until it encounters the null terminator (‘\0’), which signifies the end of the string. For each character encountered, increments the length counter. Once the loop completes then returns the length which will give the length of the string.

  1. Create a variable length to 0.
  2. Use any loop to iterate through each character of the string until the null character (‘\0’) is encountered.
  3. Increment the length variable in each iteration.
  4. After the loop, the length variable will contain the actual length of the string.

C Program to Find the Length of the String Using a Loop

C
// C program to find the length of a string manually using a loop
#include <stdio.h>

int stringLen(char *str)
{
    int length = 0;
  
    // Loop till the NULL character is found
    while (*str != '\0')
    {
        length++;

        // Move to the next character
        str++;
    }
    return length;
}

int main()
{
    char str[1000] = "GeeksforGeeks";
    int length = stringLen(str);
    printf("Length of the String is %d", length);

    return 0;
}

Output
Length of the String is 13

2. Find the Length of a String using strlen()

We can find the length of the string using the strlen() function. It is defined inside the strlib.h library.

Syntax of strlen()

int strlen(char* str);

C Program to Find the Length of a String using strlen()

C
// C program to find the length of
// string using strlen function
#include <stdio.h>
#include <string.h>

int main()
{
    char str[1000] = "GeeksforGeeks";

    // Calling strlen with Str as argument
      int len = strlen(str);
    printf("Length of the String is %d", len);

    return 0;
}

Output
Length of the String is 13

3. Find the Length of a String Using Pointer Subtraction

We can use pointer subtraction technique to find the length of string. When we subtract the address of the first character from the address of the null terminator, the result tells us how many characters are in between, which equals the string’s length. Each character occupies one byte, so the difference directly represents the number of characters.

  • Create a pointer to the first character of the string ptr = &str[0].
  • Create a loop that runs till the pointer points to the null and in each iteration, increment the pointer.
  • Use pointer subtraction to find the difference between the pointer at the end of the string and the pointer at the start (i.e, length = (ptr – &str[0])
  • Return the difference as length.

C Program to Find the Length of a String Using Pointer Subtraction

C
// C program to find the size of string by pointer
// substraction
#include <stdio.h>

int stringLen(char *str)
{
    // Start pointer pointing at the beginning
    char *ptr = &str[0];

    // Move the pointer until it points to null character
    while (*ptr)
        ptr++;

    // Difference between the address will give the length
    return ptr - str;
}

int main()
{
    char str[] = "GeeksforGeeks";

    //
    int length = stringLen(str);
    printf("Length of the String is %d\n", length);
    return 0;
}

Output
Length of the String is 13

Frequently Asked Questions (FAQs) on Finding Length of String in C

Which method should I use to find the length of a string?

For simplicity and readability, using the strlen function is recommended. However, understanding the manual counting method and pointer subtraction can be useful for learning purposes.

Does the length include the null character (‘\0’)?

No, the length of a string is the number of characters excluding the null character (‘\0’).

Can we use the sizeof operator to find the size of a string?

The sizeof operator returns the total size of the memory allocated for an array, including any unused space, rather than the actual length of the string stored within it. This means that sizeof gives the size of the entire array (e.g., char str[100] would give 100), not the number of characters in the string.

Also, strings are sometimes represented as pointers and the sizeof operator will only return the size of that pointer.

Related Articles:



Previous Article
Next Article

Similar Reads

Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible". Examples: Input: str = "0000100001100001”, K = 4O
14 min read
Minimize steps to form string S from any random string of length K using a fixed length subsequences
Given a string S consisting of N characters and a positive integer K, the task is to find the minimum number of operations required to generate the string S from a random string temp of size K and inserting the subsequence of any fixed length from the random string in the random string. If it is impossible to generate the string S, then print "-1".
12 min read
Minimum length of the sub-string whose characters can be used to form a palindrome of length K
Given a string str consisting of lowercase English letters and an integer K. The task is to find the minimum length of the sub-string whose characters can be used to form a palindrome of length K. If no such sub-string exists then print -1.Examples: Input: str = "abcda", k = 2 Output: 5 In order to form a palindrome of length 2, both the occurrence
14 min read
Construct a string of length L such that each substring of length X has exactly Y distinct letters
Given the length of the string l, the length of the substring x and the number of distinct characters that a substring of length x must have are y, the task is to find a string of length l in which every substring of length x has y distinct characters.Examples: Input: l = 6, x = 5, y = 3 Output: abcabc Explanation: If we take a substring of the fir
4 min read
Generate an N-length string having longest palindromic substring of length K
Given two integers N and K (K ? N), the task is to obtain a string of length N such that maximum length of a palindromic substring of this string is K. Examples: Input: N = 5, K = 3 Output: "abacd" Explanation: Palindromic substrings are "a", "b", "c", "d" and "aba". Therefore, the longest palindromic substring from the given string is of length 3.
4 min read
Find length of smallest substring of a given string which contains another string as subsequence
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. If there are multiple such substrings in A, return the substring that has the smallest starting index. Examples : Input : A = "abcedbaced" B = "bed"Output : "bced"Explanation : The substring A[2 : 5] is the shortest substring that contains the stri
15 min read
How to find length of a string without string.h and loop in C?
Find the length of a string without using any loops and string.h in C. Your program is supposed to behave in following way: Enter a string: GeeksforGeeks (Say user enters GeeksforGeeks) Entered string is: GeeksforGeeks Length is: 13 You may assume that the length of entered string is always less than 100.The following is the solution. C/C++ Code #i
2 min read
Find length of longest subsequence of one string which is substring of another string
Given two strings X and Y. The task is to find the length of the longest subsequence of string X which is a substring in sequence Y. Examples: Input : X = "ABCD", Y = "BACDBDCD" Output : 3 "ACD" is longest subsequence of X which is substring of Y. Input : X = "A", Y = "A" Output : 1Recommended PracticeFind length of longest subsequenceTry It! PRERE
15+ min read
Lex program to find the Length of a String
Problem: Write a Lex program to find the Length of a String Explanation: FLEX (Fast Lexical Analyzer Generator) is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
1 min read
Find the length of the median of a Triangle if length of sides are given
Given the length of all three sides of a triangle as a, b and c. The task is to calculate the length of the median of the triangle.  A median of a triangle is a line segment joining a vertex to the midpoint of the opposite side, thus bisecting that side.   Examples:   Input: a = 8, b = 10, c = 13 Output: 10.89Input: a = 4, b = 3, c = 5 Output: 3.61
4 min read
Minimum length of string having all permutation of given string.
Given a string [Tex]S [/Tex]where [Tex]1\leq length\; of\; S\leq 26 [/Tex]. Assume that all the characters in [Tex]S [/Tex]are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present as a substring in the resulting string. Examples:
4 min read
Minimum characters to be replaced to make a string concatenation of a K-length palindromic string
Given a string S of size N and a positive integer K ( where N % K = 0), the task is to find the minimum number of characters required to be replaced such that the string is K-periodic and the K-length periodic string must be a palindrome. Examples: Input: S = "abaaba", K = 3Output: 0Explanation: The given string is already K-periodic and the period
11 min read
Length of String formed by repeating each character in range [L, R] of given string its lexicographic value times
Given a string S of length N, and a range [L, R] (1 &lt;= L, R &lt;= N). The task is to find the length of string formed by repeating each character in the range [L, R], to its lexicographical value times. Examples: Input: s = "cbbde", l = 2, r = 5Output: 13Explanation: Resultant String is formed after repeating each character in range [2, 5] as sh
9 min read
Minimize length of prefix of string S containing all characters of another string T
Given two string S and T, the task is to find the minimum length prefix from S which consists of all characters of string T. If S does not contain all characters of string T, print -1. Examples: Input: S = "MarvoloGaunt", T = "Tom" Output: 12 Explanation: The 12 length prefix "MarvoloGaunt" contains all the characters of "Tom" Input: S = "TheWorld"
7 min read
Length of longest substring to be deleted to make a string equal to another string
Given two strings str1 and str2, where str2 is a subsequence of str1, the task is to find the length of the longest substring of str1 which when removed, makes the strings str2 and str1 equal. Examples: Input: str1 = “programmingbloods”, str2 = “ibloods” Output: 8 Explanation: Substrings to be removed from str1 are [“program”, “ng”]. Therefore, the
9 min read
Minimize length of a string by removing occurrences of another string from it as a substring
Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S[3]} and modifies the remaining string to "abcbd".
8 min read
Partition a string into palindromic strings of at least length 2 with every character present in a single string
Given a string S consisting of N lowercase alphabets, the task is to check if all the strings of at least length 2 formed by selecting every character of the string S only once are palindromic or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "abbbaddzcz"Output: YesExplanation: The palindromic strings of len
10 min read
Lexicographically shortest string of length at most K which is not a substring of given String
Given a string S, the task is to find the lexicographically shortest string of length less than or equal to K which is not a substring of the given string. If not possible, print -1. Examples: Input: S = zxabcehgf, K = 2Output: dExplanation: Lexicographically, the shortest string which is not a substring of a given string is d. Input: S = sdhaacbde
9 min read
Return a Palindromic String after removing minimum length Prefix from given String
Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanation: We can remove the prefix "a" from the string "a
5 min read
Check if a string contains a palindromic sub-string of even length
S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given string and check if any of them is a palindrome. Thi
8 min read
Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = "abcdefababaef", B = "abf"Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = "abcdefababaef", B = "aef"Output: 3 Recommended: Please solve it on "PRACT
12 min read
C Program to Print the Length of a String using Pointers
Prerequisite: Pointer in C This article demonstrates the program to find the length of the string using pointers in C. Examples: Input : given_string = "geeksforgeeks"Output : length of the string = 13 Input : given_string = "coding"Output : length of the string = 6 Approach: In this program, we make use of the (*) dereference operator. The (*) der
2 min read
Program for length of a string using recursion
Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 We have discussed 5 Different methods to find length of a string in C++ How to find length of a string without string.h and loop in C? Algorithm: recLen(str) { If str is NULL return 0 Else return 1 + recLe
3 min read
C program to print the length of a String using %n format specifier
Given string str. The task is to find the length of the string using %n format specifier Examples: Input: Geeks For Geeks Output: 15 Input: Geeks Output: 5 Approach: To find the length of string, we use special format specifier “%n” in printf function. In C printf(), %n is a special format specifier which instead of printing something causes printf
1 min read
Cut all the rods with some length such that the sum of cut-off length is maximized
Given N rods of different lengths. The task is to cut all the rods with some maximum integer height 'h' such that the sum of cut-off lengths of the rod is maximized and must be greater than M. Print -1 if no such cut is possible. Note: A rod cannot be cut also. Examples: Input: N = 7, M = 8, a[] = {1, 2, 3, 5, 4, 7, 6} Output: 3 Rod 1 and 2 are unt
9 min read
Length of the chord the circle if length of the another chord which is equally inclined through the diameter is given
Given are two chords which are equally inclined through the diameter of the circle. Length of one chord is given. The task is to find the length of another chord.Examples: Input: z = 48 Output: 48 degrees Input: z = 93 Output: 93 degrees Approach: Let AB and AC be the two chords of the circle having the center at O.now, in the figure we see, OL is
3 min read
Maximum length L such that the sum of all subarrays of length L is less than K
Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 20 Output: 5 The only subarray of length 5 is the complete array and (1 + 2 + 3 + 4 + 5) = 15 &lt; 20. Input: arr[] = {1, 2, 3, 4, 5}, K = 10
8 min read
Length of longest Palindromic Subsequence of even length with no two adjacent characters same
Given a string str, the task is to find the length of the longest palindromic subsequence of even length with no two adjacent characters same except the middle characters. Examples: Input: str = "abscrcdba" Output: 6 Explanation: abccba is the required string which has no two consecutive characters same except the middle characters. Hence the lengt
11 min read
Length of longest subarray of length at least 2 with maximum GCD
Given an array arr[] of length N, the task is the find the length of longest subarray of length at least 2 with maximum possible GCD value.Examples: Input: arr[] = {1, 2, 2} Output: 2 Explanation: Possible sub-arrays of size greater than 2 and there GCD’s are: 1) {1, 2} -&gt; 1 2) {2, 2} -&gt; 2 3) {1, 2, 3} -&gt; 1 Here, the maximum GCD value is 2
7 min read
Minimize number of cuts required to break N length stick into N unit length sticks
Given an integer N denoting the length of a given stick, the task is to minimize the time required to split the stick into pieces of unit length, given that, a single cut is possible for any portion of stick at any instance of time. Examples: Input: N = 100 Output: 7 Explanation: (100 units) ---&gt; (2 portions of 50 units) ---&gt; (4 portions of 2
5 min read