- 0
Notifications Mark All Read
- Login
- Get Prime
Python Program for Calculating the length of string Without using length() function
Calculating the length of the string without using length() function
Every datatype that stores some value have some length and length of a variable only can be calculated if its datatype can be iterated just like String can be iterated but Integer datatypes are not iterated. One way to find the length of String is by using in-built function len() and the other is by iterating through the string and incrementing the counter by one till loop ends.
Algorithm
- Step 1:- Start.
- Step 2:- Take user input.
- Step 3:- Initialize a count variable.
- Step 4:- Start a for loop by iterating every element of a string.
- Step 5:- Increment count variable by 1.
- Step 6:- Print count.
- Step 7:- End.
Python program to find length of a string without using in-built function
Run
#take user input
string = 'Hello'
count = 0
for i in string:
count+=1
print(count)
5
Note
The time complexity of this code is O(n) and if you are using the build in function like strlen or length the time complexity will still be same O(n)
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment
S=input(“enter a string:”)
Count=0
For i in s:
Count=count+1
Print(count)
str=input()
print(len(str))
def Scount(a, count):
for i in a:
count +=1
return count
if __name__==”__main__”:
print(Scount(input(“”), 0))
count = 0
for i in input(“Enter a string – “):
count+=1
print(count)
s=input()
count=0
for i in s:
count=count+1
print(count)
a=str(input())
list1=[]
list1[0:]=a
count=0
for i in range(0,len(list1)):
count+=1
print(count)
char = input(“enter the string”)
k = len(str(char))
print(k)