How should I get the total no. of substrings in a string. For all substrings in a string.
Ex:
str="This is this my book is This"
O/p should like below:
This-3
Is=2
my=1
book=1
How should I get the total no. of substrings in a string. For all substrings in a string.
Ex:
str="This is this my book is This"
O/p should like below:
This-3
Is=2
my=1
book=1
If I'm right you want to search for the occurrences of all words, not all possible substrings. A very small, easy to understand, code would be the following:
// Split at space
String[] words = input.split(" ");
HashMap<String, Integer> countingMap = new HashMap<>();
for (String word : words) {
Integer counter = countingMap.get(word);
if (counter == null)) {
counter = 0;
}
countingMap.put(word, counter + 1);
}
However, this approach is limited as it assumes each word is surrounded by a space.
Regex is a more powerful tool, it provides a special character for a word boundary (this also matches ,.!? and so on). Consider the following Pattern:
\b(.+?)\b
You can see an example here: regex101.com/r/hO8kA0/1
How to do this in Java?
Pattern pattern = Pattern.compile("\\b(.+?)\\b");
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
String word = matcher.group(1);
// Here is your word, count the occurrences like above
}
If I understood you correctly this is a solution for your problem:
String str="This is this my book is This";
Map<String, Integer> counts = new HashMap<String, Integer>();
String[] words = str.toLowerCase().split("[\\s\\.,;!\\?]");
for (String word: words) {
int count = counts.containsKey(word) ? counts.get(word).intValue() : 0;
counts.put(word, Integer.valueOf(count + 1));
}
You just split the string by the delimiters you want to consider and collect the occurrences in a map.
String str="This is this my book is This";
String[] words = str.split(" ");
Map<String,Integer> unitwords = new HashMap<String,Integer>;
for(String word: words){
if(unitwords.containsKey(word)){
unitwords[word]++;
}else{
unitwords.add(word,1);
}
And print the map unitwords.