In this example, we will find the length of string
#include <iostream>
#include <string.h>
using namespace std;
int main(){
string str = "OceanLabz";
//By Function
//Length of string using size() methode
cout<< str.size() <<endl;
//Length of string using length methode
cout<< str.length() <<endl;
//By logic
//1
int i=0;
while(str[i])
i++;
cout<< i << endl;
//2
for( i = 0; str[i]; i++);
cout<< i << endl;
return 0;
}
Output:
9
9
9
9
Explanation:
Step1: String Declaration
string str = "OceanLabz";
Here, a string str
is declared and initialized with the value "OceanLabz"
. The length of this string is 9 characters.
Step2: Finding the Length Using Built-in Methods
Using size()
Method
cout<< str.size() << endl;
- The
size()
method returns the number of characters in the stringstr
. - In this case, it will return
9
, since"OceanLabz"
has 9 characters.
Using length()
Method
cout<< str.length() << endl;
- The
length()
method is equivalent tosize()
and returns the number of characters in the stringstr
. - It also returns
9
.
Both size()
and length()
are functionally identical for C++ std::string
objects, providing the length of the string.
Step3: Finding the Length Using Logic (Manual Counting)
Logic 1: Using while
Loop
int i = 0;
while(str[i])
i++;
cout<< i << endl;
- This loop manually counts the characters in the string.
str[i]
accesses each character in the string. The loop runs until it encounters the null terminator (\0
), which signifies the end of the string.- Each time the loop iterates,
i
is incremented, effectively counting the characters. - After the loop finishes,
i
holds the length of the string, which is printed as9
.
Logic 2: Using for
Loop
for(i = 0; str[i]; i++);
cout<< i << endl;
- This
for
loop does the same thing as thewhile
loop but in a more compact form. - The loop runs as long as
str[i]
is not the null terminator (\0
), incrementingi
at each step. - Once the loop ends,
i
will hold the length of the string, which is printed as9
.