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

โปรแกรม Python คำนวณความยาวสตริงโดยไม่ใช้ Library Function


เมื่อต้องการหาความยาวสตริงโดยไม่ใช้ len() ให้วนลูปนับตัวอักษรด้วยตัวแปรนับ

ตัวอย่างโค้ด

my_string = "Hi Will"
print("The string is:", my_string)

count = 0
for ch in my_string:
    count += 1

print("The length of the string is:", count)

ผลลัพธ์

The string is: Hi Will
The length of the string is: 7

คำอธิบาย

  • เริ่มต้นตัวนับที่ 0

  • วนลูป for ch in my_string ทุกตัวอักษรเพิ่มตัวนับ 1

  • รวมเว้นวรรคและอักขระพิเศษด้วย

  • เป็นวิธีการทำงานภายในของ len() สำหรับ sequence types