Find the length of a String
Last Updated :
09 Oct, 2023
Given a string str, the task is to find the length of the string.
Examples:
Input: str = “Geeks”
Output: Length of Str is : 5
Input: str = “GeeksforGeeks”
Output: Length of Str is: 13
Approach 1: Iterative(using Loop)
The most traditional method of finding the length of the string is by traversing each character through the loop.
- Using a counter, traverse each character of the string with the help of Loop.
- Update the counter for every character
- When the string is terminated or a null character is identified, break the loop.
- Return the counter value as the length of the string.
Below is the implementation of the above method:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "GeeksforGeeks" ;
int i = 0, cnt = 0;
while (str[i]) {
i++;
cnt++;
}
cout << cnt << endl;
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int main()
{
char Str[] = "GeeksforGeeks" ;
int i = 0, cnt = 0;
while (Str[i]) {
cnt++;
i++;
}
printf ( "%d" , cnt);
return 0;
}
|
Java
public class StringLength {
public static void main(String[] args) {
String str = "GeeksforGeeks" ;
int i = 0 , cnt = 0 ;
while (i < str.length()) {
i++;
cnt++;
}
System.out.println(cnt);
}
}
|
Python3
str = "GeeksforGeeks"
i = 0
cnt = 0
while str [i:]:
i + = 1
cnt + = 1
print (cnt)
|
C#
using System;
class Program {
static void Main( string [] args) {
string str = "GeeksforGeeks" ;
int length = str.Length;
Console.WriteLine(length);
}
}
|
Javascript
let str = "GeeksforGeeks" ;
let i = 0, cnt = 0;
while (str[i] !== undefined) {
i++;
cnt++;
}
console.log(cnt);
|
Time Complexity: O(N), where N is the length of the string.
Auxillary space: O(1)
Approach 2: Using In-built methods
Every programming language offers a built-in method as well to find the length of the string, such as:
C
|
strlen()
|
C++
|
size()
|
Java
|
length()
|
Python
|
len()
|
Javascript
|
length
|
C#
|
length()
|
Below is the implementation of the above methods:
C++
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string str = "GeeksforGeeks" ;
cout << str.size() << endl;
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int main()
{
char Str[] = "GeeksforGeeks" ;
printf ( "%ld" , strlen (Str));
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
int stringSize = str.length();
System.out.println(stringSize);
}
}
|
Python
str = "GeeksforGeeks"
print ( len ( str ))
|
C#
using System;
class Program
{
static void Main()
{
string str = "GeeksforGeeks" ;
Console.WriteLine(str.Length);
Console.ReadLine();
}
}
|
Javascript
let str = "GeeksforGeeks" ;
let length = str.length;
console.log(length);
|
Time Complexity: O(1), except strlen() for C it is O(N)
Auxillary Space: O(1)
Share your thoughts in the comments
Please Login to comment...