java word count
package com.company;
import java.util.*;
public class Main{
public static int countWords(String s)
{
int count=0;
char ch[]= new char[s.length()];
for(int i=0;i<s.length();i++)
{
ch[i]= s.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
count++;
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Give word:");
String word = in.nextLine();
System.out.println(countWords(word) + " words.");
}
}
3.86
7
String name = "Carmen is a fantastic play"; //arbitrary sentence
int numWords = (name.split("\\s+")).length; //split string based on whitespace
//split returns array - find legth of array
System.out.println(numWords);
Thank you!
7
0
4.4
10
public static void main(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.");
}
Thank you!
10
0
3.8
10
public static void main(String[] args)
{
//Scanner object instantiation
Scanner dude = new Scanner(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");
}
Thank you!
10
0
Are there any code examples left?
New code examples in category Java
-
Java 2022-03-27 21:35:04 Sort string array in case insensitive order and case sensitive order java
-
Java 2022-03-27 21:25:10 java -jar -l resources\es.porperties -i ejemplo.txt -o inject.bin
-
Java 2022-03-27 21:20:21 Debug & Fix a 2-Dimensional Array Java Console Application
-
Java 2022-03-27 20:40:19 TreeSet headSet(E toElement) method in java
-
Java 2022-03-27 19:30:06 close keyboard android
-
Java 2022-03-27 19:20:40 java measure execution time
-
Java 2022-03-27 19:10:06 how to add cardview support in android studio
-
Java 2022-03-27 18:55:08 android studio lower case letters on a button