Finding the longest word ArrayList /Java - java

I want to write a method which finds the longest String (word). The output should be the longest word in case of two words with the same lenght the output should be: "More than one longest word".
I used ArrayList and almost had a solution, but something goes wrong. The case is that I have a problem when two words have the same lenght.
The output is :
More than one longest word
More than one longest word
14 incrementation is the longest word
Please check out piece of my code and help me to find the answer :)
public class LongestWord {
public static void main(String[] args) {
ArrayList<String> wordsList = new ArrayList<String>();
wordsList.add("december");
wordsList.add("california");
wordsList.add("cat");
wordsList.add("implementation");
wordsList.add("incrementation");
int largestString = wordsList.get(0).length();
int index = 0;
for (int i = 0; i < wordsList.size(); i++) {
if (wordsList.get(i).length() > largestString) {
largestString = wordsList.get(i).length();
index = i;
}else if(wordsList.get(i).length() == largestString){
largestString = wordsList.get(i).length();
index = i;
System.out.println("More than one longest word");
}
}
System.out.println(largestString +" " + wordsList.get(index) +" is the longest word ");
}
}

The fact is that you can't tell what the biggest word until you have iterated the whole list.
So iterate on the list
if word is bigger than previous largest size : clear list and save word
if word has same size as largest size : save word
if word is smaller : nothing
List<String> wordsList = Arrays.asList(
"december", "california", "cat",
"implementation", "incremntation");
int maxLength = Integer.MIN_VALUE;
List<String> largestStrings = new ArrayList<>();
for (String s : wordsList) {
if (s.length() > maxLength) {
maxLength = s.length();
largestStrings.clear();
largestStrings.add(s);
} else if (s.length() == maxLength) {
largestStrings.add(s);
}
}
if (largestStrings.size() > 1) {
System.out.println("More than one longest word");
System.out.println(largestStrings);
} else {
System.out.println(largestStrings.get(0) + " is the longest word");
}
Gives
More than one longest word
[implementation, incrementation]

azro is right. You can figure out the problem using two iteration. I m not sure but the code below works
for (int i = 0; i < wordsList.size(); i++) {
if (wordsList.get(i).length() > largestString) {
largestString = wordsList.get(i).length();
index = i;
}
}
for (int i = 0; i < wordsList.size(); i++) {
if (wordsList.get(index).length() == wordsList.get(i).length()) {
System.out.println("More than one longest word");
break;
}
}

You can do this with one loop iteration. Storing the longest word(s) as you go.
import java.util.*;
public class Test {
public static void main(String[] args) {
final Collection<String> words = Arrays.asList(
"december", "california", "cat",
"implementation", "incrementation");
final Collection<String> longestWords = findLongestWords(words);
if (longestWords.size() == 1) {
System.out.printf("The longest word is: %s\n", longestWords.iterator().next());
} else if (longestWords.size() > 1) {
System.out.printf("More than one longest word. The longest words are: %s\n", longestWords);
}
}
private static final Collection<String> findLongestWords(final Collection<String> words) {
// using a Set, so that duplicate words are stored only once.
final Set<String> longestWords = new HashSet<>();
// remember the current length of the longest word
int lengthOfLongestWord = Integer.MIN_VALUE;
// iterate over all the words
for (final String word : words) {
// the length of this word is longer than the previously though longest word. clear the list and update the longest length.
if (word.length() > lengthOfLongestWord) {
lengthOfLongestWord = word.length();
longestWords.clear();
}
// the length of this word is currently though to be the longest word, add it to the Set.
if (word.length() == lengthOfLongestWord) {
longestWords.add(word);
}
}
// return an unmodifiable Set containing the longest word(s)
return Collections.unmodifiableSet(longestWords);
}
}

My two cents to make it done in the single loop. Can be improved further.
ArrayList<String> wordsList = new ArrayList<String>();
wordsList.add("december");
wordsList.add("california");
wordsList.add("cat");
wordsList.add("implementation");
wordsList.add("incrementation");
String result;
int length = Integer.MIN_VALUE;
Map<String,String> map = new HashMap<>();
for(String word: wordsList){
if(word.length() >= length) {
length = word.length();
if (map.containsKey(String.valueOf(word.length())) || map.containsKey( "X" + word.length())) {
map.remove(String.valueOf(word.length()));
map.put("X" + word.length(), word);
} else {
map.put(String.valueOf(word.length()), word);
}
}
}
result = map.get(String.valueOf(length)) == null ? "More than one longest word" :
map.get(String.valueOf(length)) + " is the longest word";
System.out.println(result);

Here is one approach. I am using a set to hold the results as there is no reason to include duplicate words if they exist.
iterate over the words
if the current word length is > maxLength, clear the set and add the word, and update maxLength
if equal to the maxLength, just add the word.
List<String> wordsList = List.of("december", "implementation",
"california", "cat", "incrementation");
int maxLength = Integer.MIN_VALUE;
Set<String> results = new HashSet<>();
for (String word : wordsList) {
int len = word.length();
if (len >= maxLength) {
if (len > maxLength) {
results.clear();
maxLength = len;
}
results.add(word);
}
}
System.out.printf("The longest word%s -> %s%n", results.size() > 1 ? "s" : "", results);
prints
The longest words -> [implementation, incrementation]

I changed your code to suggest a different approach to the problem. Honestly, I hope you'll find it fascinating and helpful.
There are two different fashion of it, one that doesn't care about finding more than one longest word (it stamps just the first one - but you can change it as you prefer), and the other one that does.
First solution:
`
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class LongestWord {
public static void main(String[] args) {
List<String> wordsList = new ArrayList<>();
wordsList.add("december");
wordsList.add("california");
wordsList.add("cat");
wordsList.add("implementation");
wordsList.add("incrementation");
wordsList.stream()
.max(LongestWord::compare)
.ifPresent(a -> System.out.println(a.toUpperCase() + " is the longest word with length of: " + a.length()));
}
private static int compare(String a1, String b1) {
return a1.length() - b1.length();
}
}
`
Second solution:
`
public class LongestWord {
public static void main(String[] args) {
List<String> wordsList = new ArrayList<>();
wordsList.add("december");
wordsList.add("california");
wordsList.add("cat");
wordsList.add("implementation");
wordsList.add("incrementation");
int max_length = wordsList.stream()
.max(LongestWord::compare)
.map(String::length).orElse(0);
List<String> finalWordsList = wordsList.stream()
.filter(word -> word.length() == max_length)
.collect(Collectors.toList());
if (finalWordsList.size() > 1) {
System.out.println("More than one longest word");
} else {
System.out.println(finalWordsList.get(0) + " is the longest word");
}
}
private static int compare(String a1, String b1) {
return a1.length() - b1.length();
}
}
`

Related

Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase

I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:
string = "good morning everyone"
n = 2
Output = gOod mOrning eVeryone
for (int x = 0; x < s.length(); x++)
if (x == n-1){
temp+=(""+s.charAt(x)).toUpperCase();
}else{
temp+=(""+s.charAt(x)).toLowerCase();
}
s=temp;
System.out.println(s);
}
Output: gOod morning everyone
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.
This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.
public class Test {
static String test = "This is a test.";
public static void main(String[] args) {
String[] words = test.split(" ");
String result = "";
for (String word : words) {
result += nthToUpperCase(word, 2);
result += " ";
}
System.out.println(result);
}
public static String NthToUpperCase(String s, int n) {
String temp = "";
for (int i = 0; i < s.length(); i++) {
if (i == (n-1)) {
temp+=Character.toString(s.charAt(i)).toUpperCase();
} else {
temp+=Character.toString(s.charAt(i));
}
}
return temp;
}
}
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.
toUpperCase(2, "good morning everyone");
private static void toUpperCase(int nth, String sentence) {
StringBuilder result = new StringBuilder();
for(String word : sentence.split(" ")) {
for(int i = 0; i < word.length(); i++) {
if(i > 0 && i % nth - 1 == 0) {
result.append(Character.toString(word.charAt(i)).toUpperCase());
} else {
result.append(word.charAt(i));
}
}
result.append(" ");
}
System.out.println(result);
}
gOoD mOrNiNg eVeRyOnE

Evil Hangman Java Program

I am working on a Evil Hangman Program And for some reason I am getting this error:
What length word do you want to use? 4
How many wrong answers allowed? 4
guesses : 4
guessed : []
current : ----
Your guess? e
Exception in thread "main" java.lang.NullPointerException
at Game.HangmanManager.record(HangmanManager.java:142)
at Game.HangmanMain.playGame(HangmanMain.java:62)
at Game.HangmanMain.main(HangmanMain.java:42)
Here is my program:
package Game;
import java.util.*;
public class HangmanManager
{
private String pattern;
private int max;
private int length;
private SortedSet<Character> guessesMade;
private Set<String> currentWords;
private Map<String, Set<String>> patternMap;
public HangmanManager(List<String> dictionary , int length, int max)
{
this.max = max;
this.length = length;
if( length < 1 && max < 0)
{
throw new IllegalArgumentException();
}
words = new TreeSet<String>();
guessesMade = new TreeSet<Character>();
currentWords = new TreeSet<String>(); // current words =(words)
patternMap = new TreeMap<String, Set<String>>(); // patternMAP = < pattern, words>
for (String word : dictionary)
{
if (word.length() == length)
{
words.add(word); // if length of the word matches a word with the same length it will be added
}
}
}
public Set<String> words()
{
return words;
}
public int guessesLeft()
{
return max - guessesMade.size();
}
public SortedSet<Character> guesses()
{
return guessesMade;
}
public String pattern()
{
if (words.isEmpty())
{
throw new IllegalArgumentException("Invalid No Words");
}
pattern = " "; // blank for now
for (int i = 0; i < length; i++)
{
pattern += "-"; // will have a "-" for how long the length of the word is
}
return pattern; // will return the number of lines
}
public int record(char guess)
{
if (guessesLeft() < 1 || words.isEmpty())
{
throw new IllegalStateException();
}
if (!words.isEmpty() && guessesMade.contains(guess))
{
throw new IllegalArgumentException();
}
guessesMade.add(guess); // guess
int occurences = 0;
for( String word: words)
{
if( patternMap.containsKey (pattern))
{
occurences = generatePattern(word, guess); // the word including the guess letter will fill in the blank spots
currentWords.add(word); // the word will be added to the possibilities
currentWords = patternMap.get(pattern); // the word will be able to fill once the guesses are made
// if(patternMap.get(pattern)!=null)
// {
// currentWords = patternMap.get(pattern);
//
// }
patternMap.put(pattern, currentWords);
}
else
{
currentWords.add(word);
patternMap.put(pattern, currentWords);
}
}
words = find();
return occurences;
}
private Set<String> find()
{
int maxSize = 0;
Map <String, Integer> patternCount = new TreeMap<String, Integer>();
for (String key : patternMap.keySet()) // keyset equals word
{
patternCount.put(key, patternMap.get(key).size()); // size of the word
if (patternMap.get(key).size() > maxSize)
{
maxSize = patternMap.get(key).size();
pattern = key; // pattern will becomes based on the word
} else if (patternMap.get(key).size() == maxSize)
{
if (key.length() >= pattern.length())
{
pattern = key;
maxSize = patternMap.get(key).size(); // the pattern is now the word key
}
}
}
System.out.println("Current pattern: " + pattern);
return patternMap.get(pattern); // the pattern that will becomes now that the word was picked
}
private int generatePattern(String s, char guess)
{
int count = 0;
pattern = "";
for (int i = 0; i < length; i++)
{
if (s.charAt(i) == guess)
{
pattern += guess + " ";
count++;
} else
{
pattern += "- ";
}
}
return count;
}
}
The error seems to happen in the record method for the :
patternMap.put(pattern, currentWords); on Line 149
I ran the debugger numerous times and I do notice that if you follow the program you will see that currentWords becomes Null eventually after the program runs through the words after one time even though I instantiate it and I created a Map for patternMap.
If anyone can tell me what to do or what to change I will really appreciate it because I am so lost with this
patternMap is a TreeMap. As you said, your problem is with patternMap.put(pattern, currentWords); on line 149. According to the JavaDocs for TreeMap, put() throws NullPointerException...
if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since a TreeMap<String,Object> uses natural ordering of it's keys (i.e. String), the problem is that pattern is null. Why don't you just initialize pattern to a default value:
private String pattern = " ";

sub arraylist's size isn't correct

After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());

Adding Results of Recursion to An ArrayList

I'm trying to find all permutations of a word and add that to an Arraylist and return the array list. But, I believe my recursion is right but, there is a problem with adding the results to the ArrayList.This is what I have so far. The parameters I passed were "eat" and "" and what is returned is "tea" three times
public static ArrayList<String> permutations(String word, String beginning)
{
int l = word.length();
ArrayList<String> temp = new ArrayList<String>();
if(l == 0)
temp.add(beginning + word);
else
{
char c = word.charAt(l-1);
String blah = (beginning + c);
word = word.substring(0, l-1);
for(int i = 0; i < l; i++)
{
permutations(word, blah);
temp.add(blah + word);
}
}
return temp;
}
Probably I didn't have the right idea of your approach to find an easy fix and by the time I got things working I ended up with this. I hope it isn't too much of a departure and that it's still helpful. The output is:
[tea, tae, eta, eat, ate, aet]
import java.util.ArrayList;
public class Perm {
public static void main(String[] args) {
ArrayList<String> perms = new ArrayList<String>();
permutations("tea", perms);
System.out.println(perms);
}
public static ArrayList<String> permutations(String word, ArrayList<String> perms)
{
int l = word.length();
// If the word has only a single character, there is only
// one permutation -- itself. So we add it to the list and return
if (l == 1) {
perms.add(word);
return perms;
}
// The word has more than one character.
// For each character in the word, make it the "beginning"
// and prepend it to all the permutations of the remaining
// characters found by calling this method recursively
for (int i=0; i<word.length(); ++i) {
char beginning = word.charAt(i);
// Create the remaining characters from everything before
// and everything after (but not including) the beginning char
String blah = word.substring(0,i)+word.substring(i+1);
// Get all the permutations of the remaining characters
// by calling recursively
ArrayList<String> tempArray = new ArrayList<String>();
permutations(blah, tempArray);
// Prepend the beginning character to each permutation and
// add to the list
for (String s : tempArray) {
perms.add(beginning + s);
}
}
return perms;
}
}

Count the number of Occurrences of a Word in a String

I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:
i have a male cat. the color of male cat is Black
Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!
What I am trying is:
int c = 0;
for (int j = 0; j < text.length(); j++) {
if (text.contains("male cat")) {
c += 1;
}
}
System.out.println("counter=" + c);
it gives me 46 counter value! So whats the solution?
You can use the following code:
String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
i++;
}
System.out.println(i); // Prints 2
Demo
What it does?
It matches "male cat".
while(m.find())
indicates, do whatever is given inside the loop while m finds a match.
And I'm incrementing the value of i by i++, so obviously, this gives number of male cat a string has got.
If you just want the count of "male cat" then I would just do it like this:
String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);
and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:
int c = str.split("\\bmale cat\\b").length - 1;
StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.
String input = "i have a male cat. the color of male cat is Black";
int occurance = StringUtils.countMatches(input, "male cat");
System.out.println(occurance);
Java 8 version:
public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}
Java 8 version.
System.out.println(Pattern.compile("\\bmale cat")
.splitAsStream("i have a male cat. the color of male cat is Black")
.count()-1);
This static method does returns the number of occurrences of a string on another string.
/**
* Returns the number of appearances that a string have on another string.
*
* #param source a string to use as source of the match
* #param sentence a string that is a substring of source
* #return the number of occurrences of sentence on source
*/
public static int numberOfOccurrences(String source, String sentence) {
int occurrences = 0;
if (source.contains(sentence)) {
int withSentenceLength = source.length();
int withoutSentenceLength = source.replace(sentence, "").length();
occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
}
return occurrences;
}
Tests:
String source = "Hello World!";
numberOfOccurrences(source, "Hello World!"); // 1
numberOfOccurrences(source, "ello W"); // 1
numberOfOccurrences(source, "l"); // 3
numberOfOccurrences(source, "fun"); // 0
numberOfOccurrences(source, "Hello"); // 1
BTW, the method could be written in one line, awful, but it also works :)
public static int numberOfOccurrences(String source, String sentence) {
return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}
using indexOf...
public static int count(String string, String substr) {
int i;
int last = 0;
int count = 0;
do {
i = string.indexOf(substr, last);
if (i != -1) count++;
last = i+substr.length();
} while(i != -1);
return count;
}
public static void main (String[] args ){
System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}
That will show: 2
Another implementation for count(), in just 1 line:
public static int count(String string, String substr) {
return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}
Why not recursive ?
public class CatchTheMaleCat {
private static final String MALE_CAT = "male cat";
static int count = 0;
public static void main(String[] arg){
wordCount("i have a male cat. the color of male cat is Black");
System.out.println(count);
}
private static boolean wordCount(String str){
if(str.contains(MALE_CAT)){
count++;
return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
}
else{
return false;
}
}
}
public class TestWordCount {
public static void main(String[] args) {
int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
System.out.println("count : "+count);
}
public static int numberOfOccurences(String findWord, String sentence) {
int length = sentence.length();
int lengthWithoutFindWord = sentence.replace(findWord, "").length();
return (length - lengthWithoutFindWord)/findWord.length();
}
}
This will work
int word_count(String text,String key){
int count=0;
while(text.contains(key)){
count++;
text=text.substring(text.indexOf(key)+key.length());
}
return count;
}
Replace the String that needs to be counted with empty string and then use the length without the string to calculate the number of occurrence.
public int occurrencesOf(String word)
{
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replace(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
Once you find the term you need to remove it from String under process so that it won't resolve the same again, use indexOf() and substring() , you don't need to do contains check length times
The string contains that string all the time when looping through it. You don't want to ++ because what this is doing right now is just getting the length of the string if it contains " "male cat"
You need to indexOf() / substring()
Kind of get what i am saying?
If you find the String you are searching for, you can go on for the length of that string (if in case you search aa in aaaa you consider it 2 times).
int c=0;
String found="male cat";
for(int j=0; j<text.length();j++){
if(text.contains(found)){
c+=1;
j+=found.length()-1;
}
}
System.out.println("counter="+c);
This should be a faster non-regex solution.
(note - Not a Java programmer)
String str = "i have a male cat. the color of male cat is Black";
int found = 0;
int oldndx = 0;
int newndx = 0;
while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
{
found++;
oldndx = newndx+8;
}
There are so many ways for the occurrence of substring and two of theme are:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
We can count from many ways for the occurrence of substring:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
I've got another approach here:
String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";
// Split description using "hello", which will return
//string array of words other than hello
String[] words = description.split("hello");
// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
lengthOfNonMatchingWords += word.length();
}
// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " +
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());
Complete Example here,
package com.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class WordsOccurances {
public static void main(String[] args) {
String sentence = "Java can run on many different operating "
+ "systems. This makes Java platform independent.";
String[] words = sentence.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (int i = 0; i<words.length; i++ ) {
if (wordsMap.containsKey(words[i])) {
Integer value = wordsMap.get(words[i]);
wordsMap.put(words[i], value + 1);
} else {
wordsMap.put(words[i], 1);
}
}
/*Now iterate the HashMap to display the word with number
of time occurance */
Iterator it = wordsMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
+entryKeyValue.getValue()+" times");
}
}
}
public class WordCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String scentence = "This is a treeis isis is is is";
String word = "is";
int wordCount = 0;
for(int i =0;i<scentence.length();i++){
if(word.charAt(0) == scentence.charAt(i)){
if(i>0){
if(scentence.charAt(i-1) == ' '){
if(i+word.length()<scentence.length()){
if(scentence.charAt(i+word.length()) != ' '){
continue;}
}
}
else{
continue;
}
}
int count = 1;
for(int j=1 ; j<word.length();j++){
i++;
if(word.charAt(j) != scentence.charAt(i)){
break;
}
else{
count++;
}
}
if(count == word.length()){
wordCount++;
}
}
}
System.out.println("The word "+ word + " was repeated :" + wordCount);
}
}
Simple solution is here-
Below code uses HashMap as it will maintain keys and values. so here keys will be word and values will be count (occurance of a word in a given string).
public class WordOccurance
{
public static void main(String[] args)
{
HashMap<String, Integer> hm = new HashMap<>();
String str = "avinash pande avinash pande avinash";
//split the word with white space
String words[] = str.split(" ");
for (String word : words)
{
//If already added/present in hashmap then increment the count by 1
if(hm.containsKey(word))
{
hm.put(word, hm.get(word)+1);
}
else //if not added earlier then add with count 1
{
hm.put(word, 1);
}
}
//Iterate over the hashmap
Set<Entry<String, Integer>> entry = hm.entrySet();
for (Entry<String, Integer> entry2 : entry)
{
System.out.println(entry2.getKey() + " "+entry2.getValue());
}
}
}
public int occurrencesOf(String word) {
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replaceAll(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
for scala it's just 1 line
def numTimesOccurrenced(text:String, word:String) =text.split(word).size-1

Categories