A string is a sequence of characters, where each character has an assigned index. It is similar to an array of characters. It can contain any character like a-z, A-Z, 0-9, white spaces and special characters. The index of the characters in a string starts from 0 and goes till length of the string – 1. Special characters and white spaces also have an assigned index.
For example, if we consider the string “It’s okay.”
The indexing will be as follows:
Characters I t ‘ s o k a y .
Index 0 1 2 3 4 5 6 7 8 9
We can perform a lot of string manipulation tasks using various programming languages. With the help of these indexes, we can calculate the frequency of each character present in the array. In this article, we will see how we can calculate the frequency of punctuation marks present in a string given by the user.
In this algorithm, we first take the string as input from the user. Then, we calculate the length of the string and store it in a variable, say ‘l’. After that, we initialize the frequency of punctuations, say ‘f’ as zero. We initialize a loop variable, say i as zero and start a loop which runs from i to length of the string – 1. We now find out the character present at index i and store it in a variable say ‘c’.
We will now compare c with each of the punctuation mark: ‘,’ , ‘.’ , ‘;’ , ‘/’, ‘-‘ , ‘:’, ‘?’, ‘!’, ‘ “ ‘. If a match is found, we increment the frequency by 1. Once the execution of this loop ends, we will have the frequency of the punctuation marks in the variable f. We can now print this frequency.
Let us consider an example:
Input: “ It’s sunny outside, isn’t it? ”
Here, the punctuations in the string are:’ ‘ ‘, ‘,’ and ‘?’
So, the output will be: 4