在 Python 程式中輸入兩個字串並顯示較長的字串(不使用內建函式)
如果需要輸入兩個字串並在不使用任何內建函式的情況下顯示較長的字串,則可以使用計數器來獲取字串的長度,並且可以使用“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。
迭代第一個字串並透過增加計數器來確定其長度。
對第二個字串也執行相同操作。
將這些計數相互比較。
根據結果,在控制檯上顯示輸出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP