Count no. of characters and words in a string in PL/SQL

PL/SQLMySQLDatabase

We are given a string of any length and the task is to calculate the count of characters and words in a string using PL/SQL.

PL/SQL is a combination of SQL along with the procedural features of programming languages.It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL. PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and Java.

In PL/SQL block, we have DECLARE block which is used to declare the variables used in programming and we have BEGIN block where we write the logic for the given problem,

For Example

Input − string str = “Tutorials Point”
Output− count of characters is: 15
      Count of words are: 2

Explanation-: In the given string we have a total 2 words so word count is 2 and in those words we have 14 characters plus one is for one space in a given string.

Input − string str = “Honesty is the best policy”
Output − count of characters is: 26
      Count of words are: 5

Explanation − In the given string we have a total 5 words so word count is 5 and in those words we have 24 characters plus four is for four spaces in a given string.

Approach used in the below program is as follows

  • Input the string of any length and store it in a variable let’s say, str

  • Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.

  • Traverse the loop starting from i to 0 and till length of a string str

  • Use function substr() that will return the number of substrings in a string that is the number of words in a string

  • And, increase the count of characters with every iteration of a loop which is going till the length of a string.

  • Print the count of characters and words in a string.

Example

DECLARE
      str VARCHAR2(40) := 'Tutorials Point';
      nchars NUMBER(4) := 0;
      nwords NUMBER(4) := 1;
      s CHAR;
BEGIN
   FOR i IN 1..Length(str) LOOP
      s := Substr(str, i, 1);
      nchars:= nchars+ 1;
      IF s = ' ' THEN
      nwords := nwords + 1;
      END IF;
END LOOP;
dbms_output.Put_line('count of characters is:'
   ||nchars);

dbms_output.Put_line('Count of words are: '
   ||nwords);
END;

Output

If we run the above code it will generate the following output −

count of characters is: 15
Count of words are: 2
raja
Published on 15-May-2020 13:50:31
Advertisements