C Program to Find Length of String

Get Certified in C Programming for Free and Take Your Skills to the Next Level

Determining the length of a string is a common task in programming. It allows us to perform operations on strings of text in an abstract way without needing to know the exact contents.

Strings are represented as arrays of characters in C programming, and they are terminated by the null character “/0”. To find the length of a C string, we need to iterate through the characters until we encounter the null terminator.

In this article, we will learn how to write a C program that can find and print the length of a string input by the user. Being able to manipulate strings is a fundamental skill in C that allows programmers to write code that can handle text input and output.

Understanding Strings in C

A string in C is simply an array of char data types. The difference between a regular array and a string is that strings are terminated with a special null character ‘\0’. This null character signals the end of the string.

For example:

char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Here, str is a char array that can hold six characters. The last element is ‘\0’, which marks the end of the string.

Note that in C, strings are always one element longer than the actual string length to accommodate the null terminator.

Algorithm to Find String Length in C

Here is a step-by-step algorithm to find the length of a string in C:

1. Start with an index variable at 0 to track the current position in the string.
2. Verify that the character at the present index is ‘/0’.
3. If it is, we have reached the end of the string. Return the index as the string length.
4. If not, increment the index and repeat steps 2 onwards.

In pseudocode:

Initialize index = 0 

While str[index] is not equal to '\0'
   Increment index
   
Return index

This traverses the string until it hits the null character, counting the index value along the way.

Algorithm to Find String Length

Methods To Find String Length in C

There are several different ways to find the length of a string in C programming. Here are 4 common methods:

1) Using a Loop

One way is to use a for loop to iterate through each character of the string, incrementing a counter variable for each character. The loop continues until it reaches the null terminator ‘\0’ at the end of the string. The final count gives the length. This manual counting approach works for both arrays and pointers.

2) Using strlen()

The strlen() function is a standard C library function that returns the length of the string passed to it. It loops through the string in the background and returns the number of characters before the terminating null byte. This provides a simple way to get the length.

3) Using sizeof()

The sizeof operator returns the total allocated size in bytes of an array or pointer variable. For strings, we can use sizeof(string) – 1 to get the length, as the null terminator byte is included in the size returned by sizeof().

4) Using Pointer Difference

We can use pointers to manually iterate through the string and find the length. This involves initializing two pointers to the start of the string, incrementing the second pointer until it reaches null, and then finding the difference between the two pointers. This gives the number of characters iterated, i.e. the string length.

Steps to Determine C String Length Using Various Methods

Using a Loop

  • Initialize counter variable to 0
  • Use for loop to traverse string characters
  • Increment counter for each character
  • Loop until null terminator ‘\0’ is reached
  • Counter variable contains string length
  • Counts characters manually by iterating through the string

Using strlen()

  • Declare char array or pointer to store string
  • Call strlen(), pass string as argument
  • It returns length of string (excluding null terminator)
  • Library function handles iterating and counting internally

Using sizeof()

  • Declare char array to store entire string
  • Apply sizeof() on array, which returns total bytes
  • Subtract 1 to exclude the null terminator byte
  • Returns allocated size of array in bytes, including null terminator

Using Pointer Arithmetic

  • Initialize pointer to start of string
  • Increment second pointer until it reaches null
  • Subtract pointers to get number of characters iterated
  • Manual iteration by incrementing pointer and calculating difference

C Program Implementation

Here are various ways to implement a C program to find the length of a string:

1. Using a Loop

#include <stdio.h>

int main() {

  char str[100];
  int i, len;

  printf("Enter a string: ");
  scanf("%s", str);

  // initialize i to start at 0
  i = 0; 
  
  // iterate until null character is reached
  while(str[i] != '\0') {
    i++;
  }

  len = i;

  printf("Length of string: %d", len);
  
  return 0;
}

Output:
Enter a string: Hi
Length of string: 2

This program takes string input from the user using scanf. A while loop is used to iterate through the characters, incrementing variable i in each iteration until the null terminator is reached. The final value of i is assigned to len, which stores the string length.

Time Complexity: O(N)
Auxiliary Space: O(1)

2. Using strlen()

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

int main() {

  char str[100];

  printf("Enter a string: ");
  scanf("%s", str);
  
  int len = strlen(str);

  printf("Length of string: %d", len);
  
  return 0;
}

Output:
Enter a string: DataFlair
Length of string: 9

strlen() automatically iterates through the string and returns the length, saving us from writing the manual iteration loop.

Time Complexity: O(1)
Auxiliary Space: O(1)

3. Using sizeof()

#include <stdio.h>

int main() {

  char str[100] = "Hello";
  
  int len = sizeof(str) / sizeof(str[0]);
  
  printf("Length: %d", len);
  
  return 0;
}

Output:
Length of string: 5

sizeof(str) returns the total array size, divided by single element size gives the length.

Time Complexity: O(1)
Auxiliary Space: O(1)

4. Using Pointer Subtraction

#include <stdio.h>

int main() {
  char *start, *end;
  int len;

  // Define the input string as "coding"
  char input[] = "coding";
  
  // Initialize the start and end pointers
  start = input;
  end = input;

  // Move the end pointer to the end of the string
  while (*end != '\0') {
    end++;
  }

  // Calculate the length
  len = end - start;

  printf("Length: %d", len);

  return 0;
}

Output:
Length of string: 6

By subtracting the starting and ending pointers, we get the string length.

Time Complexity: O(n)
Space Complexity: O(1)

Example Usage

Here are some examples of how the program handles different string inputs:

1. Input: Hello

Output: Length of string: 5

2. Input: DataFlair

Output: Length of string: 9

3. Input: Programming in C is fun!

Output: Length of string: 23

The program correctly prints the length for strings of different content and sizes.

Code Explanation

Let’s go over the key aspects of each technique:

  • The manual loop increments an index variable until the null terminator is reached.
  • strlen() handles the iteration internally and returns the length.
  • sizeof() leverages the size of the entire array vs a single element.
  • Pointer subtraction finds the difference between the starting and ending pointer locations.

Choosing which method to use depends on the requirements and constraints of the program.

Common Pitfalls and Error Handling in C

Some common mistakes when finding string length in C:

  • Forgetting to initialize variables properly
  • Not allocating enough buffer size
  • Improper null termination handling
  • Buffer overflows from invalid user input

To avoid bugs, be careful when incrementing i in the loop and check for null termination properly.

Also, input validation can be added to sanitize user input and prevent buffer overflows from overly long strings.

Conclusion

This article covered different techniques like loops, strlen(), sizeof(), and pointer subtraction to find the length of a string in C. Calculating string lengths is an important skill that helps manipulate textual data. The methods here can be applied to solve more complex string problems.

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *