สมมติว่าเรามี 'สตริง' และ 'คำ' และเราจำเป็นต้องค้นหาจำนวนการเกิดคำนี้ในสตริงของเราโดยใช้ python นี่คือสิ่งที่เราจะทำในส่วนนี้ นับจำนวนคำในสตริงที่กำหนดแล้วพิมพ์ออกมา
นับจำนวนคำในสตริงที่กำหนด
วิธีที่ 1:การใช้ for loop
#วิธีที่ 1:ใช้สำหรับวนซ้ำ
test_stirng = input("String to search is : ")
total = 1
for i in range(len(test_stirng)):
if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'):
total = total + 1
print("Total Number of Words in our input string is: ", total) ผลลัพธ์
String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language Total Number of Words in our input string is: 16
#วิธีที่ 2:การใช้ while loop
test_stirng = input("String to search is : ")
total = 1
i = 0
while(i < len(test_stirng)):
if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'):
total = total + 1
i +=1
print("Total Number of Words in our input string is: ", total) ผลลัพธ์
String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language Total Number of Words in our input string is: 16
#วิธีที่ 3:การใช้ฟังก์ชัน
def Count_words(test_string):
word_count = 1
for i in range(len(test_string)):
if(test_string[i] == ' ' or test_string == '\n' or test_string == '\t'):
word_count += 1
return word_count
test_string = input("String to search is :")
total = Count_words(test_string)
print("Total Number of Words in our input string is: ", total) ผลลัพธ์
String to search is :Python is a high level language. Python is interpreted language. Python is general-purpose programming language Total Number of Words in our input string is: 16
ด้านบนเป็นวิธีอื่นๆ อีกสองสามวิธีในการค้นหาจำนวนคำในสตริงที่ผู้ใช้ป้อน