you can do this easy and quick with:
String phrase = "word1 word2 word3 word4";
String delims = " "; //u can declare more delims here like delims = " ,.{[]}\";
String[] tokens = phrase.split(delims);
tokens.length = number of words in your string
Question
So I am trying to make a word count program where the user can paste text in to get a word count of type text in to get a word count. The typing text in works for the most part but sometimes I get a string index out of range error when I try to go back and replace text. The pasting works but I am having issues with the string index being out of range issue here as well. My logic works like this: a space equals a word, two spaces back to back is minus one word, and the end of the string counts as a word. I am relatively new to Java and I thought this was going to be an easy thing to make, I was wrong! Some help/explanation would be appreciated!
public static int getWordCount(String getInput, int e){
int numberOfWords = 0;
char l1 = 0;
char l2 = 0;
StringBuilder convertInput = new StringBuilder(getInput);
System.out.println(convertInput);
for (int i = 0, i1 = 1; i < getInput.length();i++, i1++){
l2 = convertInput.charAt(i);
if (l2 == ' '){
numberOfWords += 1;
l1 = convertInput.charAt(i1);
}
if (i == getInput.length() - 1){
numberOfWords += 1;
}
if (l2 == ' ' && l1 == ' '){
numberOfWords -= 1;
}
}
return numberOfWords;
} // end of getWordCount method
Solution
you can do this easy and quick with:
String phrase = "word1 word2 word3 word4";
String delims = " "; //u can declare more delims here like delims = " ,.{[]}\";
String[] tokens = phrase.split(delims);
tokens.length = number of words in your string