LAB: Count input length without spaces, periods, or commas

Given a line of text as input, output the number of characters excluding spaces, periods, or commas. You may assume that the input string will not exceed 50 characters.

Ex: If the input is:

Listen, Mr. Jones, calm down.
the output is:

21
Note: Account for all characters that aren't spaces, periods, or commas (Ex: "r", "2", "!").

Respuesta :

Answer:

import re

str1= input("Enter the sentence less than 50 characters: ")

pattern = '[a-zA-Z]'

count=0

i=0

while(i<=len(str1)-1):

   result = re.match(pattern, str1)

   if (result):

       count+=1

   else:

       continue

   i+=1

print("String Length:",count)

Explanation:

I have used here the re library that is meant for the regular expressions in  Python.

The code below is in Java

It uses built-in methods replaceAll() and length() to calculate the length of a String

The replaceAll() method takes two arguments and replaces all the occurrences of the first argument with the second argument.

The length method returns the length of the String.

Comments are used to explain the each line.

//Main.java

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

    //declare the Scanner object to get input

    Scanner input = new Scanner(System.in);

    //declare the variables

    String line, cleanedLine = "";

    int count;

   

    //get the input

    line = input.nextLine();

   

    //remove the spaces, periods, and commas by using the replaceAll() method

    cleanedLine = line.replaceAll("[ .,]", "");

   

    //get the length of the cleanedLine by using the length() method

       count = cleanedLine.length();

       

       //print the count

       System.out.println(count);

 

}

}

You may check another String question at:

https://brainly.com/question/14889036