How to Find Length of a String in C++
-
Using the
length()
Method -
Using the
size()
Method -
Using a
for
Loop to Count Characters -
Use the
while
Loop to Find Length of a String in C++ -
Use the
std::strlen
Function to Find Length of a String in C++ - Conclusion
- FAQ

In the world of programming, understanding how to manipulate strings is crucial, especially in C++. One of the fundamental operations you’ll encounter is determining the length of a string. Knowing the length of a string can help you manage data more efficiently, whether you’re validating user input, processing text files, or simply displaying information to users.
In this article, we will explore various methods to find the length of a string in C++. We’ll delve into built-in functions, string libraries, and custom implementations, ensuring you have a comprehensive understanding of this essential topic. Let’s get started!
Using the length()
Method
The simplest way to find the length of a string in C++ is by using the length()
method, which is a member function of the std::string
class. This method returns the number of characters in the string, excluding the null terminator. Here’s a quick example:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "Length of the string: " << str.length() << std::endl;
return 0;
}
Output:
Length of the string: 13
In this code, we first include the necessary headers and create a string variable str
initialized with “Hello, World!”. By calling str.length()
, we retrieve the length of the string, which is 13 characters. The length()
method is straightforward and efficient, making it the go-to choice for many developers. It’s worth noting that this method works seamlessly with both standard strings and strings containing special characters, ensuring accurate length calculations in various scenarios.
Using the size()
Method
Another method to find the length of a string in C++ is by using the size()
method. This method serves a similar purpose as length()
, and you can use either interchangeably. Here’s how you can implement it:
#include <iostream>
#include <string>
int main() {
std::string str = "Learning C++";
std::cout << "Size of the string: " << str.size() << std::endl;
return 0;
}
Output:
Size of the string: 13
In this example, we again create a string variable str
with the text “Learning C++”. By calling str.size()
, we obtain the size of the string, which also returns 13. The size()
method is particularly useful when working with containers in C++, as it provides a consistent way to check the number of elements or characters. This method is just as efficient as length()
, and the choice between the two often comes down to personal preference.
Using a for
Loop to Count Characters
If you want to understand the underlying mechanics of string length calculation, you can implement a custom function that counts the characters in a string using a loop. This method is more educational than practical but can be useful for learning purposes. Here’s how you can do it:
#include <iostream>
#include <string>
int stringLength(const std::string& str) {
int length = 0;
for (char c : str) {
length++;
}
return length;
}
int main() {
std::string str = "Custom Length Function";
std::cout << "Length of the string: " << stringLength(str) << std::endl;
return 0;
}
Output:
Length of the string: 24
In this code snippet, we define a custom function stringLength
that takes a string as an argument. Inside the function, we initialize a counter variable length
and iterate through each character in the string using a range-based for loop. For every character encountered, we increment the length
counter. Finally, we return the total count. While this method is less efficient than using built-in functions, it provides insight into how string lengths can be calculated programmatically.
Use the while
Loop to Find Length of a String in C++
Alternatively, one can implement his/her own function to calculate the length of the string. In this case, we utilize the while
loop to traverse the string as a char
sequence and increment the counter by one each iteration. Notice that the function takes char*
as an argument, and the c_str
method is called to retrieve this pointer in the main function. The loop stops when the dereferenced pointer value is equal to 0
, and the null-terminated string implementation guarantees that.
#include <cstring>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
size_t lengthOfString(const char *s) {
size_t size = 0;
while (*s) {
size += 1;
s += 1;
}
return size;
}
int main(int argc, char *argv[]) {
string str1 = "this is random string oiwaoj";
cout << "string: " << str1 << endl;
cout << "length: " << lengthOfString(str1.c_str()) << endl;
exit(EXIT_SUCCESS);
}
Output:
string: this is random string oiwaoj
length: 28
Use the std::strlen
Function to Find Length of a String in C++
Finally, one can resort to the old-school C string library function strlen
, which takes a single const char*
argument as our custom-defined function - lengthOfString
. These last two methods can be faulty when called on char
sequences that don’t end with a null byte, as it could access out-of-range memory during the traversal.
#include <cstring>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(int argc, char *argv[]) {
string str1 = "this is random string oiwaoj";
cout << "string: " << str1 << endl;
cout << "length: " << std::strlen(str1.c_str()) << endl;
exit(EXIT_SUCCESS);
}
Output:
string: this is random string oiwaoj
length: 28
Conclusion
Finding the length of a string in C++ is a fundamental skill that every programmer should master. Whether you choose to use the built-in length()
or size()
methods or opt for a custom loop-based solution, understanding these techniques will enhance your ability to work with strings effectively. With these methods at your disposal, you can handle string manipulation tasks with confidence, making your coding experience smoother and more efficient.
FAQ
-
What is the difference between
length()
andsize()
in C++?
Bothlength()
andsize()
return the number of characters in a string. They can be used interchangeably, as they provide the same result. -
Can I find the length of a string that contains special characters?
Yes, bothlength()
andsize()
accurately count all characters, including special characters and spaces. -
Is it necessary to include any libraries to use strings in C++?
Yes, you need to include the<string>
header to use thestd::string
class and its associated methods. -
How do I calculate the length of a string without using built-in functions?
You can implement a custom function using a loop to iterate through each character in the string and count them. -
Are there performance differences between using
length()
and a custom loop?
Yes, usinglength()
orsize()
is generally more efficient than a custom loop, as these methods are optimized for performance.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn FacebookRelated Article - C++ String
- How to Capitalize First Letter of a String in C++
- How to Find the Longest Common Substring in C++
- How to Find the First Repeating Character in a String in C++
- How to Compare String and Character in C++
- How to Get the Last Character From a String in C++
- How to Remove Last Character From a String in C++