Java function for counting word - java

Is there any default method in Java that can count total occurrence of a word? For example, how many times stack occurred in a string "stack is stack".
Edit: please only Java no third party library.

You can use StringUtils.countMatches(string, "stack") from commons-lang. This doesn't account for word boundaries, so "stackstack" will be counted as two occurences.

There is no built-in .matchCount() method. Here is my impl.
public static int matchCount(String s, String find) {
String[] split = s.split(" ");
int count = 0;
for(int i=0; i<split.length; i++){
if(split[i].equals(find)){
count++;
}
}
return count;
}
String s = "stack is stack";
System.out.println(matchCount(s, "stack")); // 2

You could use:
public static int NumTimesInString(String target, String regex)
{
return (" " + target + " ").split(regex).length - 1;
}
This will work so long as regex doesn't match a beginning or ending space... Hmm, this might not work for some cases. You might be better writing a function which uses indexOf
public static int NumTimesInString(String target, String substr)
{
int index = 0;
int count = -1;
while (index != -1)
{
index = target.indexOf(substr, index);
count++;
}
return count;
}
NOTE: not tested
Either one can be used as:
int count = NumTimesInString("hello world hello foo bar hello", "hello");
// count is 3

Related

Count Words Using indexOf

I can't use arrays, only simple Java (if, for, while, substring, length, indexOf)
public int howManyWords(String s){
myString = "I have a dream";
int count = 1;
int length = 0;
while(count>=0){
count = myString.substring(String.valueOf(length),myString.indexOf(" "));
count++;
length = myString.indexOf(" ");
}
return count;
}
Should return 4
First of all, you made infinite loop, because count is 1, and you just increase it.
Second, you haven't even try to write this code in some IDE, because it would throw you a syntax error, because you are assigning string to int, when you do count = myString.substring()
So, instead of using count in loop, you can use myString.indexOf
something like this could work if you don't care what is going to happen with myString
int count = 0;
while(myString.indexOf(" ") >= 0) {
count++;
myString = myString.substring(myString.indexOf(" ") + 1)
}
return count;
Let's assume that the string you are testing does not contain leading or trailing spaces, because that affects the solution. The example string in your question does not contain leading or trailing spaces.
Simply call method indexOf(String, int) in a loop and in each iteration you set the int parameter to one more than what you got in the previous iteration. Once the value returned by method indexOf() is -1 (minus one), you are done. But don't forget to add the last word after you exit the loop.
String myString = "I have a dream";
int count = 0;
int index = 0;
while (index >= 0 && index < myString.length()) {
index = myString.indexOf(" ", index);
System.out.println("index = " + index);
if (index >= 0) {
index++;
count++;
}
}
if (index < 0) {
count++;
}
System.out.println("count = " + count);
Edited : Added missing else case.
Try the following code :
Remove the counted words from your string using the substring and indexOf, and increment the count in each iteration.
public int countWords(String s){
String myString = "I have a dream";
int count = 0;
int length = myString.length();
while(length>0){
if((myString.indexOf(" ")!=-1) && (myString.indexOf(" ")+1)<length){
myString = myString.subString(myString.indexOf(" ")+1);
count++;
length = myString.length();
}
else {
length = 0;
break;
}
}
return count;
}
PS: Conventionally, your method names should denote actions, hence I suggested it to be countWords instead of howManyWords.

How to get the total count of occurence of a word in a sentence

I am trying to find the total count of occurrence of word in a sentence.
I tried the following code:
String str = "This is stackoverflow and you will find great solutions here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";
String findStr = "hello World";
String[] split=findStr.split(" ");
for(int i=0;i<split.length;i++){
System.out.println(split[i]);
String indexWord=split[i];
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(indexWord,lastIndex);
System.out.println(lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println("Count for word "+indexWord+" is : "+count);
}
If I am passing string like "stack solution" ,the string should be split into two(space split) and need to find the no of occurrence of each string in the sentence.The count is perfect if I pass only one word.The code has to match even substrings containing the searched string.
Eg:-In the sentence "stack" apperars three times,but the count is only 2.
Thanks.
When you increment lastIndex after a match, you mean to increment it by the length of the match (indexWord), not the length of the string of input words (findStr). Just replace the line
lastIndex += findStr.length();
with
lastIndex += indexWord.length();
try this code
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
You can use map for this as well.
public static void main(String[] args) {
String value = "This is simple sting with simple have two occurence";
Map<String, Integer> map = new HashMap<>();
for (String w : value.split(" ")) {
if (!w.equals("")) {
Integer n = map.get(w);
n = (n == null) ? 1 : ++n;
map.put(w, n);
}
}
System.out.println("map" + map);
}
Is there any reason of not using the readymade API solution in place.
This can be achieved by using the StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.
E.g.
String input = "This is stackoverflow and you will find great solutions here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";
String findStr = "stackoverflow is";
for (String s : Arrays.asList(findStr.split(" "))) {
int occurance = StringUtils.countMatches(input, s);
System.out.println(occurance);
}

How to count if a specific string matches while iterating through a loop in java?

This is for a past homework assignment that I wasn't able to complete in time. I am a new programmer struggling with this method of the program CharacterSearch. I'm stuck on which boolean logic to use for my if statement, as well as how to find matches in the phrase using the pre-defined character variable. And example test is: character = "x" , phrase = "Xerox". Whereas X and x are different. The expected output should be count = 1.
Edit: This problem should be answered without using arrays or lists.
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
Scanner jf = new Scanner(phrase);
count = 0;
for (int i = phrase.length(); i > 0; i--)
{
jf.findInLine(character);
if(jf.hasNext())
{
count++;
jf.next();
}
}
return count;
}
There you go:
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
int count = 0;
// for every character in phrase ...
for (int i = 0; i < phrase.length(); i++)
{
// ... if it is the right one ...
if(phrase.charAt(i) == character)
{
// ... increment the counter
count++;
}
}
return count;
}
You don't need any Scanner, and the code is fairly easy, readable and comprehensible.
Pretty much a duplicate of Simple way to count character occurrences in a string
I can't leave a comment yet because my rep is too low but I wanted to give you a solution you could use.
public int letterCount(String phrase)
{
count = 0;
for (int i = 0 ; i < phrase.length(); i++)
{
String myLetter = phrase.substring(i, i + 1);
if (myLetter.equals(character))
{
count++;
}
}
return count;
}
I figured out that I was iterating in the wrong direction, but more importantly I was not declaring a sub-string to check if my character matched the individual letters within the phrase.
Use String's substring with a compare().
public int letterCount(String phrase, String match)
{
int count = 0;
for(int i=0;i<phrase.length()-1;i++){ //-1 avoid out-of-bound exception
String letter = phrase.substring(i, i+1);
if(letter.compareTo(match) == 0){
count++;
}
}
return count;
}

Repetition of a word in String with out using collections

Can any one suggest me to write a logic for this without using collections.
I have a string s="This is the place called island and it is a nice place ";
Input String to find repetition word is: "is";
output should be : 4
You can follow the below logic to do it.
Split the String on whitespace.
Initialize an integer counter to 0.
Traverse through each of the elements of the resultant array and for each String element of the array, do the following:
a) If stringElement.contains("is"), increment the counter created in step 2.
b) If !stringElement.contains("is"), do nothing and move on to the next element.
Do this till you exhaust all the elements of the array.
Print the counter value.
Try to write the code for this on your own and get back here if you're stuck up anywhere.
As simple as
int count = 0;
for (int startIndex = 0; startIndex >= 0; startIndex = str.indexOf("is", startIndex)) {
count++;
}
Use the following method, it should work:
public static int countSubStrings(String subString, String mainString){
return (mainString.length() - mainString.replace(subString, "").length()) / subString.length();
}
string s="This is the place called island and it is a nice place ";
s = s+" ";
System.out.println(s.split("is").length-1);
you can use this. Hope you are using Java.
public static void main(String[] args) {
String str = "This is the place called island and it is a nice place";
Pattern pattern = Pattern.compile("is");
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 4
}
this method will count how many time s2 appears in s1
public static int CountStr(String s1,String s2){
int cnt=0,temp=0;
if(s1.indexOf(s2)>0){
temp=s1.indexOf(s2);
cnt++;
}
while(s1.indexOf(s2,temp+1)>0){
cnt++;
temp=s1.indexOf(s2,temp+1);
}
return cnt;
}

Finding second occurrence of a substring in a string in Java

We are given a string, say, "itiswhatitis" and a substring, say, "is".
I need to find the index of 'i' when the string "is" occurs a second time in the original string.
String.indexOf("is") will return 2 in this case. I want the output to be 10 in this case.
Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:
str.indexOf("is", str.indexOf("is") + 1);
I am using:
Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);
This overload starts looking for the substring from the given index.
You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy
public static ArrayList<Integer> occurrencesPos(String str, String substr) {
final boolean ignoreCase = true;
int substrLength = substr.length();
int strLength = str.length();
ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();
for(int i = 0; i < strLength - substrLength + 1; i++) {
if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) {
occurrenceArr.add(i);
}
}
return occurrenceArr;
}
I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:
Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
int numOfOcurrences = 2;
for(int i = 0; i < numOfOcurrences; i++) matcher.find();
System.out.println("Index: " + matcher.start());
It seems to be a good party... I'm in:
public static int nthIndexOf(String str, String subStr, int count) {
int ind = -1;
while(count > 0) {
ind = str.indexOf(subStr, ind + 1);
if(ind == -1) return -1;
count--;
}
return ind;
}
i think a loop can be used.
1 - check if the last index of substring is not the end of the main string.
2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string
3 - repeat the steps in a loop
if you want to find index for more than 2 occurrence:
public static int ordinalIndexOf(String fullText,String subText,int pos){
if(fullText.contains(subText)){
if(pos <= 1){
return fullText.indexOf(subText);
}else{
--pos;
return fullText.indexOf(subText, ( ordinalIndexOf(fullText,subText,pos) + 1) );
}
}else{
return -1;
}
}
Anyone who is looking for Nth occurance of string
public class NthOccuranceExample {
public static void main(String[] args) {
String str1 = "helloworld good morning good evening good night";
String str2 = "ing";
int n = 2;
int index = nthOccurrence(str1, str2, n);
System.out.println("index of str2 in str1 at occurrence "+ n +" = "+ index);
}
public static int nthOccurrence(String str1, String str2, int n) {
String tempStr = str1;
int tempIndex = -1;
int finalIndex = 0;
for(int occurrence = 0; occurrence < n ; ++occurrence){
tempIndex = tempStr.indexOf(str2);
if(tempIndex==-1){
finalIndex = 0;
break;
}
tempStr = tempStr.substring(++tempIndex);
finalIndex+=tempIndex;
}
return --finalIndex;
}
}

Categories