publicstaticvoidmain(String[] args)
{
//return the number of words in a string String example ="This is a good exercise";
int length = example.split(" ").length;
System.out.println("The string is "+ length +" words long.");
}
Posted by: Guest
on June-04-2020
0
count word in string no matter the delimiter java
publicstaticvoidmain(String[] args)
{
//Scanner object instantiation
Scanner dude =newScanner(System.in);
//variable declaration String string1 ="";
int count =0;
boolean isWord =false;
//user prompt and input
System.out.println("Enter in your string");
string1 = dude.nextLine();
int endOfLine = string1.length()-1;
char ch [] = string1.toCharArray();
for (int i =0; i < string1.length(); i++)
{
if(Character.isLetter(ch[i]) && i != endOfLine)
{//if character is letter and not end of line
isWord =true; //it is part of a word
}
if (!Character.isLetter(ch[i]) && isWord)
{ //if character is not a letter, and previous //character is a letter i.e. non-letter is //preceded by character
count++; //add to word count
isWord =false; //get ready to detect new word
}
if (Character.isLetter(ch[i]) && i == endOfLine)
{ //if character is letter //and at end of line
count++; //add to word count
isWord =false;
}
}
System.out.println("There are "+count+" words");
}
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems
resetting your password contact us
Check Your Email and Click on the link sent to your email