Overview
In C, a string is an array of characters that is terminated with a null character «». The length of a string will be determined by counting all the characters in the string (except for the null character).
Scope of Article
- In this article, we will learn to find the length of a String in C.
- All the methods to find the length of a String will be explained in this article.
- Every method will be explained using syntax, images, and examples.
Introduction
The string length in C is equal to the count of all the characters in it (except the null character «»).
For Example, the string «gfddf» has a length of 5 and the string «4343» has a length of 4.
Note:
In C, a String is an array of characters that is terminated with a null character «» to indicate the end of the string.
How to Find the String Length in C?
We can find the length of a String by counting all the characters in it (before the null character) using a for loop. We can also use the built-in string.h library function strlen() or the sizeof() operator.
Let us understand how to use these methods in the coming sections.
String Length in C using a User-Defined Function
We can find the length of a string using a user-defined function by iterating over the string in a for loop and incrementing the count of characters (length) by 1 till it reaches the null character «» and then returning the count.
Let’s take a look at its implementation:
Code
// finding the length of a string using a user-defined function #include <stdio.h> // The User-defined method int str_length(char str[]) { // initializing count variable (stores the length of the string) int count; // incrementing the count till the end of the string for (count = 0; str[count] != ''; ++count); // returning the character count of the string return count; } // Driver code int main() { // initializing the array to store string characters char str[1000]; // inputting the string printf("Enter the string: "); scanf("%s", str); // assigning the count of characters in the string to the length of the string int length = str_length(str); // printing the length of string printf("The length of the string is %d", length); return 0; }
Output
Enter the string: 567lens The length of the string is 7
Explanation:
In the above example, we are finding the length of a string by iterating over it in a for loop and incrementing the count by 1 in each iteration till it reaches the null character. The value of count after the end of the for loop will be equal to the length of the string.
String Length in C Using Built-In Library Function
The length of a string can be found using the built-in library function strlen() in string.h header file. It returns the length of the string passed to it (ignoring the null character).
Syntax
The string is passed to the strlen() function, which returns its length.
Let us take a look at its implementation.
Code
// finding the length of a string using the strlen() function from the string.h library #include <stdio.h> #include <string.h> int main() { char str[1000]; // initializing the array to store string characters // inputting the string printf("Enter the string: "); scanf("%s", str); // initializing the length variable int length; // Using the strlen() function to return the length of the string and assign it to the length variable length = strlen(str); // printing the length of string printf("The length of the string is %d", length); return 0; }
Output :
Enter the string: 5654dds The length of the string is 7
In the above example, we are finding the length of a string by using the string.h library function strlen(), which returns the length of the string passed to it.
String Length in C Using the sizeof() Operator
We can also find the length of a string using the sizeof() Operator in C. The sizeof is a unary operator which returns the size of an entity (variable or value).
Syntax
The value is written with the sizeof operator which returns its size (in bytes).
Let us take a look at its implementation:
Code
// finding the length of a string using the sizeof operator #include <stdio.h> int main() { // initializing the string literal char str[] = "g4343"; // printing the string printf("The given string is %sn", str); // initializing the length variable int length; // using the sizeof operator to find the length of the string length = sizeof str; // printing the length of string printf("The length of the string is %d", length-1); return 0; }
Output
The given string is g4343 The length of the string is 5
In the above example, we are finding the length of the string «g4343» using the sizeof operator in C. The sizeof operator returns its length as 6 in the output as It returns the size of an operand, not the string length (including null values). But here, if we print length-1 then we get the length of the string.
Conclusion
- In C, the length of a string is the count of all its characters except the null character «».
- We can find the length of the string using a for loop by counting each character in each iteration.
- The built-in library function strlen() is used to return the length of a string passed to it.
- We can also find the length of a C String using the sizeof operator.
The Standard doesn’t know this «word» thingy used by processors. But it says the type «int» should have the natural size for a execution environment. But even for 64 bit environments, int is usually only 32 bits. So «word» in Standard terms has pretty much no common meaning (except for the common English «word» of course).
Character size is the size of a character. Depends on what character you talk about. Character types are char, unsigned char and signed char. Also wchar_t is used to store characters that can have any size (determined by the implementation — but must use one of the integer types as its underlying type. Much like enumerations), while char/signed char or unsigned char has to have one byte. That means that one byte has as much bits as one char has. If an implementation says one object of type char has 16 bits, then a byte has 16 bits too.
Now a byte is the size that one char occupies. It’s a unit, not some specific type. There is not much more about it, just that it is the unit that you can access memory. I.e you do not have pointer access to bit-fields, but you have access to units starting at one byte.
«Integer size» now is pretty wide. What do you mean? All of bool, char, short, int, long and their unsinged counterparts are integers. Their range is what i would call «integer size» and it is documented in the C standard — taken over by the C++ Standard. For signed char the range is from -127 <-> 127, for short and int it is the same and is -2^15+1 <-> 2^15-1 and for long it is -2^31+1 <-> 2^31-1. Their unsigned counterparts range from 0 up to 2^8-1, 2^16-1 and 2^32-1 respectively. Those are however minimal sizes. That is, an int may not have maximal size 2^14 on any platform, because that is less than 2^15-1 of course. It follows for those values that a minimum of bits is required. For char that is 8, for short/int that is 16 and for long that is 32. Two’s-complement representation for negative numbers is not required, which is why the negative value is not -128
instead of -127
for example for signed char.
How to get string length in C#?
To get the string length in C#, use the .Length property.
For example:
Examples
What is String Length in C#?
String Length in C# is a property on the String object that returns the number of characters in a string. The returned length value is of type Int32.
The Length property of a string is the number of Char objects it contains, not the number of Unicode characters.
The length property returns the number of Char objects instead of the number of Unicode characters because a Unicode character might be represented by more than one character.
What is the max string length in C#?
The maximum string length in C# is 2^31 characters. That’s because String.Length is a 32-bit integer.
How to change string length in C#?
You can’t change the string length in C#. The String.Length property is read-only.
To change the string length, you need to create a new string.
If you try to change the Length property, you will get an error:
error CS0200: Property or indexer 'string.Length' cannot be assigned to -- it is read only
How to access each Unicode character?
To access each Unicode character in a C# string, you use the System.Globalization.StringInfo class to work with each Unicode character instead of each character.
Exception
One of the most frequent null-reference exceptions is with String.Length property.
If you try to access the Length property on a null string, you will get a NullReferenceException.
Many developers forget to check for null before accessing the Length property.
Index vs Length
In C#, string length returns the number of characters in a string.
The index property returns the zero-based position of the character that is located at a specified location within an instance of String.
The length property doesn’t start at 0. It starts at the first character in the string. But the index property starts at 0.
Under the hood
Internally, C# stores strings as a read-only collection of Char
objects. There’s also a null-terminating character at the end of a C# string.
C# doesn’t count the null-terminating character in the length of a string. The null-character is just a way C# marks the end of a string under the hood.
Termination
Programming languages have different approaches to determine the string end:
- Null-terminated — Strings in C are null-terminated sequences of characters, with a special character following the last character—written «» — to show the end of the string.
- Length-prefixed -Pascal stores the length in the first bytes of the string.
- Length-and-Character Array — String as a structure with an array of characters, and stores the length in a separate allocation.
Changes in length
Programming languages have different approaches to handle changes in string length:
- Static string length is fixed and cannot be changed at runtime.
- Limited Dynamic string length can be increased or decreased, but the number of characters that can be stored in it is limited.
- Dynamic string length can grow or shrink as needed, up to the maximum size allowed by the underlying system.
In C#, strings have dynamic string length. It means that the string can grow or shrink as needed.
String class
The String class holds the implementation details and the string manipulation functionality. Looking at the source code, we can see that the string length is crucial for the string class.
Functionality such as String.Substring, String.IndexOf, and String.Remove require the length of a string in order to work correctly.
System.String class.
Published on: Feb 1, 2022
You are here
C program to find length of a string, for example, the length of the string «C programming» is 13 (space character is counted). The null character isn’t counted when calculating it. To find it, we can use strlen function of «string.h.» C program to find length of a string without using strlen function, recursion.
Length of string in C language
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf(«Enter a string to calculate its lengthn«);
gets(a);
length = strlen(a);
printf(«Length of the string = %dn«, length);
return 0;
}
Download String length program.
Output of program:
String length in C without strlen
You can also find string length without strlen function. We create our function to find it. We scan all the characters in the string if the character isn’t a null character then increment the counter by one. Once the null character is found the counter equals the length of the string.
#include <stdio.h>
int main()
{
char s[1000];
int c = 0;
printf(«Input a stringn«);
gets(s);
while (s[c] != ‘‘)
c++;
printf(«Length of the string: %dn«, c);
return 0;
}
Function to find string length:
int string_length(char s[]) {
int c = 0;
while (s[c] != ‘‘)
c++;
return c;
}
C program to find length of a string using recursion
#include <stdio.h>
int string_length(char*);
int main()
{
char s[100];
gets(s);
printf(«Length = %dn«, string_length(s));
return 0;
}
int string_length(char *s) {
if (*s == ‘‘) // Base condition
return 0;
return (1 + string_length(++s));
}
Function to find string length using pointers
int string_length(char *s) {
int c = 0;
while(*s[c] != ‘‘)
c++;
return c;
}
Home »
C programs »
C string programs
In this program, we will learn how to count length of each word in a string in C language?
There are many string manipulation programs and string user defined functions, this is an another program in which we will learn to count the length of each word in given string.
In this exercise (C program) we will read a string, like «Hi there how are you?» and it will print the word length of each word like 2, 5, 3, 3, 4.
Input
Hi there how are you?Output
2, 5, 3, 3, 4
Program to count length of each word in a string in C
#include <stdio.h> #define MAX_WORDS 10 int main() { char text[100]={0}; // to store string int cnt[MAX_WORDS]={0}; //to store length of the words int len=0,i=0,j=0; //read string printf("Enter a string: "); scanf("%[^n]s",text); //to read string with spaces while(1) { if(text[i]==' ' || text[i]=='') { //check NULL if(text[i]=='') { if(len>0) { cnt[j++]=len; len=0; } break; //terminate the loop } cnt[j++]=len; len=0; } else { len++; } i++; } printf("Words length:n"); for(i=0;i<j;i++) { printf("%d, ",cnt[i]); } printf("bb n"); //to remove last comma return 0; }
Output
Enter a string: Hi there how are you? Words length: 2, 5, 3, 3, 4
C String Programs »