I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.
Loops and if statements are okay!
I really appreciate any help I can get! Thanks!
Use the count() Method to Count Words in Python String Python. The count() method is a Python built-in method. It takes three parameters and returns the number of occurrences based on the given substring.
Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.
This would work even with multiple spaces and leading and/or trailing spaces and blank lines:
String trim = s.trim(); if (trim.isEmpty()) return 0; return trim.split("\\s+").length; // separate string around spaces
Hope that helps. More info about split here.
public static int countWords(String s){ int wordCount = 0; boolean word = false; int endOfLine = s.length() - 1; for (int i = 0; i < s.length(); i++) { // if the char is a letter, word = true. if (Character.isLetter(s.charAt(i)) && i != endOfLine) { word = true; // if char isn't a letter and there have been letters before, // counter goes up. } else if (!Character.isLetter(s.charAt(i)) && word) { wordCount++; word = false; // last word of String; if it doesn't end with a non letter, it // wouldn't count without this. } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) { wordCount++; } } return wordCount; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With