I've been trying to tweak little bits of code here and there to make my output correct. I am trying to have my code be able to rearrange the letters in a word to make other words that exist in words.txt, from https://github.com/dwyl/english-words. Any help would be appreciated. Thanks.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/Test.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
StringBuilder b = new StringBuilder();
String c = r.readLine();
while (c != null) {
b.append(c);
b.append(" ");
c = r.readLine();
}
Scanner s = new Scanner(System.in);
String in = s.nextLine();
char[] input = new char[in.length()];
for (int i = 0; i < input.length; i++) {
input[i] = in.charAt(i);
}
char[] temp = null;
for (int i = 0; i < b.length(); i++) {
if (i < b.length() - 1 && b.charAt(i) == ' ' && b.charAt(i + 1) != ' ') {
boolean found = false;
int counter = 0;
while (!found) {
counter++;
if (b.charAt(i + counter) == ' ') {
found = true;
temp = new char[counter - 1];
for (int j = i + 1; j < i + counter; j++) {
temp[j] = b.charAt(j);
}
}
}
}
}
if (Arrays.asList(input).contains(temp)) {
System.out.println(temp);
}
}
}
Here is my tweaked code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
String[] words;
String c = r.readLine();
int a=0;
while (c != null) {
c = r.readLine();
a++;
}
words=new String[a];
a=0;
r = new BufferedReader(new FileReader(file));
String temp=r.readLine();
while (temp != null) {
words[a]=r.readLine();
temp=words[a];
a++;
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input, words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input, String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
Is rearranging the characters necessary?
Rearranging the input and searching through dictionary to find equal word could take lot's of computing time, single few letter word can have many permutations.
For me, it looks like you want to find the words in dictionary for input word containing same letters (in other words, if the input word would be rearranged, it would give you the existing word in dictionary). Probably checking if both words are having exactly same letters, regardless their position in both strings should satisfy the requirement.
Here's the sample for that approach:
public class Sample {
public static void main(String[] args) {
//the words in dictionary
String[] words = {"words", "sword", "nord", "chord", "score", "cores", "mors", "xyz", "scores", "ordsw"};
String[] input = {"sword", "score", "tores", "nores"};
for (String i : input) {
List<String> found = findRearranged(i, words);
System.out.println("For '" + i + "' found: " + Arrays.toString(found.toArray()));
}
}
public static List<String> findRearranged(String input, String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
And this outputs in:
For 'sword' found: [words, sword, ordsw]
For 'score' found: [score, cores]
For 'tores' found: []
For 'nores' found: []
Edit:
I see the assumption is that every word is in its own line.
I saw that you already came up with counting the words in the file, but still in that case it's better to use Collections which are having dynamic size.
Here's fixed sample:
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "C:\\Users\\masta\\IdeaProjects\\podstawka-spring-java\\words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
List<String> words = new ArrayList<>();
String c = r.readLine();
while (c != null) {
words.add(c);
c = r.readLine();
}
for (int i = 0; i < words.size(); i++) {
System.out.println("Words: " + words.get(i));
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input, words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input, List<String> words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
I am trying to write a code the will print TRUE when i enter a word with no vowels and will print FALSE if I enter a word with vowels. I am having trouble when it comes to writing the string. I give one of the strings the value that holds all the values.
String A = "aeiou";
The other 2 strings hold the rest of the alphabet.
When I type in a word that has vocals it prints FALSE however when I type in a word with no vowels it prints FALSE.
I wanna know if there is a way to make the program read the values of the string as separate entities and not as a whole line.
package lab3;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
/* A and B, but not C */
String A = "bcdfghjklm";
String B = "npqrstvwxyz";
String C = "aeiou";
if (input.contains(A) && input.contains(B) || input.contains(C)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
You can do it with a short function
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
System.out.println(chk(input));
}
static public boolean chk(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) != -1) {
return false;
}
}
return true;
}
}
This is a working correct for your purpose:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
String C = "aeiou";
for (int i = 0; i < input.length(); i++) {
char inputA = input.charAt(i);
for (int j = 0; j < C.length(); j++) {
char c = C.charAt(j);
if (inputA == c) {
System.out.println("TRUE");
return;
}
}
}
System.out.println("FALSE");
}
The key point is to use the method charAt(int index); so you can check each char in the string.
You can choose to use any of the below two methods, containsVowel and containsVowel1 as both of them do the same thing:
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a text: ");
String input = reader.nextLine();
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(!containsVowel(input, vowels));
System.out.println(!containsVowel1(input, vowels));
}
public static boolean containsVowel(String input, String[] vowels) {
return Arrays.stream(vowels).parallel().anyMatch(input::contains);
}
public static boolean containsVowel1(String input, String[] vowels) {
for (int i = 0; i < vowels.length; i++) {
if (input.contains(vowels[i])) {
return true;
}
}
return false;
}
}
I have am assignment suppose there is a string 11234aBcD the out put should be 1a1B2c3D4 and I am unable to do it, First and the second output I have done. And I have to do using java.
I am adding my code:
package Testx;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Test3optmz {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner gaba = new Scanner( System.in );
String variable;
System.out.print("Enter String:");
variable = gaba.nextLine();
SeparateGaba(variable);
}
public static void SeparateGaba(String str)
{
String Catch_num = "";
String Catch_let = "";
String upper="";
String lower="";
String holdl="";
String holdn="";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
Catch_num = Catch_num + a;
} else
{
Catch_let = Catch_let + a;
}
}
System.out.println("FIRST OUTPUT:"+Catch_num+Catch_let);// i am separating the numbers and alphabets
for(int j=0;j <Catch_let.length();j++)
{
char x = Catch_let.charAt(j);
if (Character.isUpperCase(x))
{
upper += x;
}
else
{
lower += x;
}
}
char[] num = Catch_num.toCharArray();
Arrays.sort(num);
String n =new String(num);
char[] ordr = lower.toCharArray();
Arrays.sort(ordr);
String alfa1 =new String(ordr);
char[] ord = upper.toCharArray();
Arrays.sort(ord);
String alfa =new String(ord);
String t= alfa1 + alfa;
char [] fin = t.toCharArray();
Arrays.sort(fin);
String fal = new String(fin);
Character[] chars = new Character[fal.length()];
for (int f=0; f < fal.length();f++)
chars[f] = fal.charAt(f);
Arrays.sort(chars, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
fal = sb.toString();
System.out.println("SECOND OUTPUT= "+n+fal);// now i am arranging the alphabet in ascending order avoiding capital and small ex 1234eBaC it will come as 1234aBce
}
}
well thanks for not helping me out i helped my self
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner gaba = new Scanner( System.in );
String variable;
System.out.print("Enter String:");
variable = gaba.nextLine();
SeparateGaba(variable);
}
public static void SeparateGaba(String str)
{
String Catch_num = "";
String Catch_let = "";
String upper="";
String lower="";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
Catch_num = Catch_num + a;
} else
{
Catch_let = Catch_let + a;
}
}
System.out.println("FIRST OUTPUT:"+Catch_num+Catch_let);
for(int j=0;j <Catch_let.length();j++)
{
char x = Catch_let.charAt(j);
if (Character.isUpperCase(x))
{
upper += x;
}
else
{
lower += x;
}
}
char[] num = Catch_num.toCharArray();
Arrays.sort(num);
String n =new String(num);
char[] ordr = lower.toCharArray();
Arrays.sort(ordr);
String alfa1 =new String(ordr);
char[] ord = upper.toCharArray();
Arrays.sort(ord);
String alfa =new String(ord);
String t= alfa1 + alfa;
char [] fin = t.toCharArray();
Arrays.sort(fin);
String fal = new String(fin);
Character[] chars = new Character[fal.length()];
for (int f=0; f < fal.length();f++)
chars[f] = fal.charAt(f);
Arrays.sort(chars, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
fal = sb.toString();
System.out.println("SECOND OUTPUT= "+n+fal);
/*GABA come on let seeeeeeeee*/
try
{
for(int i=0;i<n.length();i++)
{
char a= n.charAt(i);
System.out.print(a);
for(int j=0; j<fal.length();j++)//1
{
char b = fal.charAt(j);
if(j>=i)
{
System.out.print(b);
break;
}
}
}
}
catch(Exception e)
{
System.out.println("Your letter length should match with char len");
}
}
}
Enter String:14a5Bc
FIRST OUTPUT:145aBc
SECOND OUTPUT= 145aBc
THE out put i was looking for --->1a4B5c
i have to do a program which takes a sentence and reverses it word by word in java. for eg:
India is my country
output:aidnI si ym yrtnuoc
ive figured out all of it but i just cant split a sentence into separate words.im not allowed to use split function but im meant to use either substring or indexof();while loop and for loop are allowed.
this is what ive got so far:
import java.io.*;
public class Rereprogram10
{
public void d()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("input a string");
str=br.readLine();
String rev="";
int length=str.length();
int counter=length;
for(int i=0;i<length;i++)
{
rev=rev+str.charAt(counter-1);
counter--;
}
System.out.println("the result is: "+rev);
}
}
its wrong though,the output keeps on coming:
yrtnuoc ym si aidnI
i havent learnt arrays yet...
I'm going to assume that advanced datastructures are out, and efficiency is not an issue.
Where you are going wrong is that you are reversing the entire string, you need to only reverse the words. So you really need to check to find where a word ends, then either reverse it then, or be reversing it as you go along.
Here is an example of reversing as you go along.
int length=str.length();
String sentence="";
String word = "";
for(int i=0;i<length;i++) {
if (str.charAt(i) != ' '){
word = str.charAt(i) + word;
} else {
sentence += word +" ";
word = "";
}
}
sentence += word;
System.out.println("the result is: "+sentence);
This passes the test:
package com.sandbox;
import com.google.common.base.Joiner;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
#Test
public void testQuestionInput() {
String input = "India is my country";
assertEquals("country my is India", reverseWords(input));
}
private String reverseWords(String input) {
List<String> words = putWordsInList(input);
Collections.reverse(words);
return Joiner.on(" ").join(words);
}
private List<String> putWordsInList(String input) {
List<String> words = new ArrayList<String>();
String word = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == ' ') {
words.add(word);
word = "";
} else {
word += c;
}
}
words.add(word);
return words;
}
}
Here is my code without split() for you.
Input:
India is my country
Output:
country my is India
aidnI si ym yrtnuoc
You can choose the output you need.
public class Reverse {
public static class Stack {
private Node[] slot = new Node[1000];
private int pos = 0;
private class Node{
private char[] n = new char[30];
private int pos = 0;
public void push(char c) {
n[pos++] = c;
}
public String toString() {
return new String(n).trim() + " "; // TODO Fix
}
}
public void push(char c) {
if(slot[pos] == null)
slot[pos] = new Node();
if(c != ' ') {
slot[pos].push(c);
} else {
slot[pos++].push(c);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = pos; i >=0; i --)
sb.append(slot[i]);
return sb.toString();
}
private String reverseWord(String word) {
StringBuilder sb = new StringBuilder();
int len = word.length();
for(int i = len - 1; i >= 0; i--)
sb.append(word.charAt(i));
return sb.toString();
}
public String foryou() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < pos + 1; i ++)
sb.append(this.reverseWord(slot[i].toString()));
return sb.toString();
}
}
/**
* #param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
String sentence = "India is my country";
System.out.println(sentence);
for(int i = 0; i < sentence.length(); i ++) {
stack.push(sentence.charAt(i));
}
System.out.println(stack);
System.out.println(stack.foryou());
}
}
try this
String x="India is my country";
StringBuilder b=new StringBuilder();
int i=0;
do{
i=x.indexOf(" ", 0);
String z;
if(i>0){
z=x.substring(0,i);
}
else{
z=x;
}
x=x.substring(i+1);
StringBuilder v=new StringBuilder(z);
b.append(v.reverse());
if(i!=-1)
b.append(" ");
System.out.println(b.toString());
}
while(i!=-1);
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!
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
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;
}
Hi I just figured out with StringTokenizer like this:
String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
Simply use ,
str.split("\\w+").length ;
public static int countWords(String str){
if(str == null || str.isEmpty())
return 0;
int count = 0;
for(int e = 0; e < str.length(); e++){
if(str.charAt(e) != ' '){
count++;
while(str.charAt(e) != ' ' && e < str.length()-1){
e++;
}
}
}
return count;
}
private static int countWordsInSentence(String input) {
int wordCount = 0;
if (input.trim().equals("")) {
return wordCount;
}
else {
wordCount = 1;
}
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
String str = new String("" + ch);
if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
Use
myString.split("\\s+");
This will work.
There is a Simple Solution You can Try this code
String s = "hju vg jhdgsf dh gg g g g ";
String[] words = s.trim().split("\\s+");
System.out.println("count is = "+(words.length));
public static int countWords(String input) {
int wordCount = 0;
boolean isBlankSet = false;
input = input.trim();
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == ' ')
isBlankSet = true;
else {
if (isBlankSet) {
wordCount++;
isBlankSet = false;
}
}
}
return wordCount + 1;
}
Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);
//google word counter
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {
wordsMultiset.add(string.toLowerCase());
}
Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
System.out.println(string+" X "+wordsMultiset.count(string));
}
add at the pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
Counting Words in a String:
This might also help -->
package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {
public static void main(String[] args) throws IOException {
// Couting number of words in a string
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter Your String");
String input = br.readLine();
char[] arr = input.toCharArray();
int i = 0;
boolean notCounted = true;
int counter = 0;
while (i < arr.length) {
if (arr[i] != ' ') {
if (notCounted) {
notCounted = false;
counter++;
}
} else {
notCounted = true;
}
i++;
}
System.out.println("words in the string are : " + counter);
}
}
public class TestStringCount {
public static void main(String[] args) {
int count=0;
boolean word= false;
String str = "how ma ny wo rds are th ere in th is sente nce";
char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++){
if(!(ch[i]==' ')){
for(int j=i;j<ch.length;j++,i++){
if(!(ch[j]==' ')){
word= true;
if(j==ch.length-1){
count++;
}
continue;
}
else{
if(word){
count++;
}
word = false;
}
}
}
else{
continue;
}
}
System.out.println("there are "+(count)+" words");
}
}
import java.util.;
import java.io.;
public class Main {
public static void main(String[] args) {
File f=new File("src/MyFrame.java");
String value=null;
int i=0;
int j=0;
int k=0;
try {
Scanner in =new Scanner(f);
while(in.hasNextLine())
{
String a=in.nextLine();
k++;
char chars[]=a.toCharArray();
i +=chars.length;
}
in.close();
Scanner in2=new Scanner(f);
while(in2.hasNext())
{
String b=in2.next();
System.out.println(b);
j++;
}
in2.close();
System.out.println("the number of chars is :"+i);
System.out.println("the number of words is :"+j);
System.out.println("the number of lines is :"+k);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My idea of that program is that:
package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoutingWords {
public static void main(String[] args) throws IOException {
String str;
int cWords = 1;
char ch;
BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text: ");
str = buffor.readLine();
for(int i =0; i<str.length(); i++){
ch = str.charAt(i);
if(Character.isWhitespace(ch)){ cWords++; }
}
System.out.println("There are " + (int)cWords +" words.");
}
}
I'm new to stackoverflow but I hope my code helps:
private int numOfWordsInLineCounter(String line){
int words = 0;
for(int i = 1 ; i<line.length();i++){
Character ch = line.charAt(i-1);
Character bch = line.charAt(i);
if(Character.isLetterOrDigit(ch) == true && Character.isLetterOrDigit(bch)== false ) words++;
if(i == line.length()-1 && Character.isLetterOrDigit(bch))words++;
}
return words;
}
A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.
import java.util.HashMap;
import java.util.Map;
public class WordCountMethod {
public static void main (String [] args){
Map<String, Integer>m = new HashMap<String, Integer>();
String phrase = "hello my name is John I repeat John";
String [] array = phrase.split(" ");
for(int i =0; i < array.length; i++){
String word_i = array[i];
Integer ci = m.get(word_i);
if(ci == null){
m.put(word_i, 1);
}
else m.put(word_i, ci+1);
}
for(String s : m.keySet()){
System.out.println(s+" repeats "+m.get(s));
}
}
}
Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:
public static int countWords(final String s) {
int wordCount = 0;
boolean word = false;
final int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (isWordCharacter(s, i) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!isWordCharacter(s, 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 (isWordCharacter(s, i) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
private static boolean isWordCharacter(final String s, final int i) {
final char ch = s.charAt(i);
return Character.isLetterOrDigit(ch)
|| ch == '\''
|| Character.getType(ch) == Character.DASH_PUNCTUATION
|| Character.isSurrogate(ch);
}
I just put this together. The incrementer in the wordCount() method is a bit inelegant to me, but it works.
import java.util.*;
public class WordCounter {
private String word;
private int numWords;
public int wordCount(String wrd) {
StringTokenizer token = new StringTokenizer(wrd, " ");
word = token.nextToken();
numWords = token.countTokens();
numWords++;
return numWords;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
WordCounter wc = new WordCounter();
System.out.println("Enter a sentence.");
userWord = input.nextLine();
wc.wordCount(userWord);
System.out.println("You sentence was " + wc.numWords + " words long.");
}
}
create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:
if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;
lambda, in which splitting and storing of the counted words is dispensed withand only counting is done
String text = "counting w/o apostrophe's problems or consecutive spaces";
int count = text.codePoints().boxed().collect(
Collector.of(
() -> new int[] {0, 0},
(a, c) -> {
if( ".,; \t".indexOf( c ) >= 0 )
a[1] = 0;
else if( a[1]++ == 0 ) a[0]++;
}, (a, b) -> {a[0] += b[0]; return( a );},
a -> a[0] ) );
gets: 7
works as a status machine that counts the transitions from spacing characters .,; \t to words
if(str.isEmpty() || str.trim().length() == 0){
return 0;
}
return (str.trim().split("\\s+").length);
String a = "Some String";
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (Character.isWhitespace(a.charAt(i))) {
count++;
}
}
System.out.println(count+1);
It will count white spaces. However, If we add 1 in count , we can get exact words.