Given the following:
String s = "The The The the the the";
How can I find how many instances of "The" are in the string s?
s.matches("The")
only tells me if it at least one is there.
s.contains("The")
is the same.
Is there some simple way?
Given the following:
String s = "The The The the the the";
How can I find how many instances of "The" are in the string s?
s.matches("The")
only tells me if it at least one is there.
s.contains("The")
is the same.
Is there some simple way?
As i know Matcher.find() method attempts to find the next subsequence of the input sequence that matches the pattern. That means you can iterate through matches calling this method multiple times:
int count = 0;
while (matcher.find()) {
count++;
}
you should use Matcher.start() and Matcher.end() to retrieve matching subsequence.
You can use indexOf(str, count)
int count = 0;
String s = "The The The the the the";
String match = "The";
int searchStart = 0;
while ((searchStart = s.indexOf(match, searchStart)) != -1)
{
count++;
searchStart+= match.length();
}
You can use s.indexOf("The", index);, if it is returning some index then increment count and the index also and make it inot a loop until the index is not found.
NOTE: Initially the value of index is 0
Give a try of this:
String test = "The The The the the the";
System.out.println(test.split("The").length);
Simply split the string on the word to be counted.
String text = "the the water the the";
System.out.println(text.split("the", -1).length -1);
Also if you are currently using apache commons lang you could use its count function from StringUtils
String text = "the the water the the";
int count = StringUtils.countMatches(text, "the");
System.out.println("count is " + count);
However don't just bring that in for that one function thats a bit of overkill :)
String s = "The The The The The sdfadsfdas";
List<String> list = Arrays.asList(s.split(" "));
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
System.out.println(key + ": " + Collections.frequency(list, key));
}