When it is required to take two strings and display the larger string without using any built-in function, the counter can be used to get the length of the strings, and ‘if’ condition can be used to compare their lengths.
Below is the demonstration of the same −
Example
string_1= "Hi there" string_2= "Hi how are ya" print("The first string is :") print(string_1) print("The second string is :") print(string_2) count_1 = 0 count_2 = 0 for i in string_1: count_1=count_1+1 for j in string_2: count_2=count_2+1 if(count_1<count_2): print("The larger string is :") print(string_2) elif(count_1==count_2): print("Both the strings are equal in length") else: print("The larger string is :") print(string_1)
Output
The first string is : Hi there The second string is : Hi how are ya The larger string is : Hi how are ya
Explanation
Two strings are defined, and are displayed on the console.
Two counter variables are initialized to 0.
The first string is iterated over and its length is determined by incrementing the counter.
The same is done for the second string as well.
These counts are compared to each other.
Depending on the value, the output is displayed on the console.