หาความยาวของคำสุดท้ายในสตริง โดยตัดช่องว่างนำ/ท้าย (strip()) แล้วนับตัวอักษรจนกว่าจะเจอช่องว่างหรือจบสตริง
ตัวอย่างโค้ด
def last_word_length(my_string):
init_val = 0
processed_str = my_string.strip()
for i in range(len(processed_str)):
if processed_str[i] == " ":
init_val = 0
else:
init_val += 1
return init_val
my_input = "Hi how are you Will"
print("The string is :")
print(my_input)
print("The length of the last word is :")
print(last_word_length(my_input))
ผลลัพธ์
The string is : Hi how are you Will
The length of the last word is : 4
คำอธิบาย
strip()ลบช่องว่างนำและท้าย- วนลูปทุกตัวอักษร: เจอช่องว่าง -> รีเซ็ตค่าเป็น 0, ไม่ใช่ -> เพิ่ม 1
- ค่าสุดท้ายก่อนจบลูปคือความยาวคำสุดท้าย
- วิธีอื่น:
len(my_string.strip().split()[-1])สั้นกว่า