Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ใช้สองสตริงและแสดงสตริงที่ใหญ่ขึ้นโดยไม่ต้องใช้ฟังก์ชันในตัวใน Python Program


เมื่อต้องใช้สองสตริงและแสดงสตริงที่ใหญ่กว่าโดยไม่ต้องใช้ฟังก์ชันในตัว สามารถใช้ตัวนับเพื่อรับความยาวของสตริง และใช้เงื่อนไข 'if' เพื่อเปรียบเทียบความยาวได้

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

ตัวอย่าง

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)

ผลลัพธ์

The first string is :
Hi there
The second string is :
Hi how are ya
The larger string is :
Hi how are ya

คำอธิบาย

  • มีการกำหนดสองสตริงและแสดงบนคอนโซล

  • ตัวแปรตัวนับสองตัวเริ่มต้นเป็น 0

  • สตริงแรกถูกวนซ้ำและความยาวถูกกำหนดโดยการเพิ่มตัวนับ

  • เช่นเดียวกันสำหรับสตริงที่สองเช่นกัน

  • นับเหล่านี้เปรียบเทียบกัน

  • ขึ้นอยู่กับค่า ผลลัพธ์จะแสดงบนคอนโซล