Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package string_methods;
- // Starting Template
- import java.util.Scanner;
- public class MyStringMethods {
- private String myStr = "";
- public void readString() {
- // Prompt the user and read in a String from a Scanner class from the keyboard
- // with the nextLine() method and store it in "myStr"
- Scanner scan = new Scanner(System.in);
- myStr = scan.nextLine();
- System.out.println("Enter String: ");
- }
- public void setString(String s) {
- myStr = s;
- }
- public int countOccurrences(String s) {
- int count = 0;
- String word[] = myStr.split(" ");
- for (int i = 0; i < word.length; i++) {
- int index = word[i].indexOf(s);
- if (index != -1);
- {
- count++;
- }
- }
- {
- return count;
- }
- // use indexOf and return the number of occurrences of the string "s" in "myStr"
- }
- public int countOccurrences(char c) {
- int count = 0;
- String word[] = myStr.split(" ");
- for (int j = 0; j < word.length; j++) {
- int index = word[j].indexOf(c);
- if (index != -1) {
- {
- count++;
- }
- }
- }
- return count;
- // use indexOf and return the number of occurrences of the character "c" in
- // "myStr"
- }
- public int countUpperCaseLetters() {
- // char[]ch=myStr.toCharArray();
- int count = 0;
- for (int i = 0; i < myStr.length(); i++)
- {
- if (Character.isUpperCase(myStr.charAt(i))) {
- count++;
- }
- }
- return count;
- // return the number of upper case letters in "myStr"
- }
- public int countLowerCaseLetters() {
- char[] ch = myStr.toCharArray();
- int count = 0;
- for (int j = 0; j < myStr.length(); j++)
- {
- if (Character.isLowerCase(myStr.charAt(j))) {
- count++;
- }
- }
- // return the number of lower case letters in "myStr"
- return count;
- }
- public void printCounts(String s, char c) {
- System.out.println("***************************************");
- System.out.println("Analyzing: myStr=" + myStr);
- System.out.println("Number of Upper case letters=" + countUpperCaseLetters());
- countUpperCaseLetters();
- System.out.println("Number of Lower case letters=" + countLowerCaseLetters());
- countLowerCaseLetters();
- System.out.println("Number of " + s + " is " + countOccurrences(s));
- System.out.println("Number of " + c + " is " + countOccurrences(c));
- }
- public static void main(String[] args) {
- MyStringMethods msm = new MyStringMethods();
- msm.readString();
- msm.printCounts("big", 'a');
- msm.setString("Parked in a van down by the river bank....The van evan vanished near a lot of other vans");
- msm.printCounts("van", 'a');
- MyStringMethods msm2 = new MyStringMethods();
- msm2.setString("the elephant in the room wouldn't budge");
- msm2.printCounts("the", 'i');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement