This is a Python Program to calculate the number of words and characters present in a string.
Problem Description
The program takes a string and calculates the number of words and characters present in the string.
Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize the character count variable to 0 and the word count variable to 1.
3. Use a for loop to traverse through the characters in the string and increment the character count variable each time.
4. Increment the word count variable only if a space is encountered.
5. Print the total count of the characters and words in the string.
6. Exit.
Program/Source Code
Here is source code of the Python Program to calculate the number of words and characters present in a string. The program output is also shown below.
string=raw_input(“Enter string:”)
char=0
word=1
for i in string:
char=char+1
if(i==’ ‘):
word=word+1
print(“Number of words in the string:”)
print(word)
print(“Number of characters in the string:”)
print(char)
Runtime Test Cases
Case 1:
Enter string:Hello world
Number of words in the string:
2
Number of characters in the string:
11
Case 2:
Enter string:I love python
Number of words in the string:
3
Number of characters in the string:
13