Problem: Capitalize first letter of each word in a sentence.
Example:
capitalize_words('This is a sample sentence')
This Is A Sample Sentence
Solution in Python:
def capitalize_words(sentence):
"""
Author: Mayur P Srivastava
"""
arr = list(sentence)
start_of_word = False
for i in range(len(arr)):
c = arr[i]
if c == ' ' or c == '\t' or c == '\n':
start_of_word = True
else:
if start_of_word:
ascii = ord(c)
start_of_word = False
if ascii >= 97 and ascii <= 122:
arr[i] = chr(ascii - 32)
return "".join(arr)
Concepts Learned: Single loop.
No comments:
Post a Comment