Problem:
Write a short Java method that uses a StringBuilder instance to remove all the
punctuation from a string s storing a sentence
Solution:
package com.basics;
import java.util.Scanner;
public class RemovePunctuationFromAString {
String sentence = "";
public static void main(String[] args) {
RemovePunctuationFromAString removePunctuationFromAString = new RemovePunctuationFromAString();
removePunctuationFromAString.getTheNumber();
System.out.println("After removing all the punctuations: " + removePunctuationFromAString.removePunctuation());
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a sentence with punctuation");
sentence = scanner.nextLine();
scanner.close();
}
public String removePunctuation(){
StringBuilder outputStr = new StringBuilder();
char[] characters = sentence.toCharArray();
int asciiValue = 0;
for (int i = 0; i < characters.length; i++) {
asciiValue = (int)characters[i];
if(!(asciiValue > 32 && asciiValue < 48)){
outputStr.append(characters[i]);
}
}
return outputStr.toString();
}
}
Output:
enter a sentence with punctuation
Let's try, Mike!
After removing the all punctuations: Lets try Mike
Write a short Java method that uses a StringBuilder instance to remove all the
punctuation from a string s storing a sentence
Solution:
package com.basics;
import java.util.Scanner;
public class RemovePunctuationFromAString {
String sentence = "";
public static void main(String[] args) {
RemovePunctuationFromAString removePunctuationFromAString = new RemovePunctuationFromAString();
removePunctuationFromAString.getTheNumber();
System.out.println("After removing all the punctuations: " + removePunctuationFromAString.removePunctuation());
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a sentence with punctuation");
sentence = scanner.nextLine();
scanner.close();
}
public String removePunctuation(){
StringBuilder outputStr = new StringBuilder();
char[] characters = sentence.toCharArray();
int asciiValue = 0;
for (int i = 0; i < characters.length; i++) {
asciiValue = (int)characters[i];
if(!(asciiValue > 32 && asciiValue < 48)){
outputStr.append(characters[i]);
}
}
return outputStr.toString();
}
}
Output:
enter a sentence with punctuation
Let's try, Mike!
After removing the all punctuations: Lets try Mike
No comments:
Post a Comment