Counting occurrences in string java

Count occurrences of substring in string in Java example

Count occurrences of a substring in string example shows how to count occurrences of a substring in string in Java using various ways.

How to count occurrences of a substring in string in Java?

There are several ways using which you can count occurrences of a substring in Java.

1) Count occurrence of a substring in a string using the indexOf method

You can count occurrences of a substring in a string using the indexOf method of the String class. Consider below given string.

Below given is the example program to find the number of occurrences of “Java” within the string.

We started off with having count and fromIndex as 0. fromIndex holds the index position from where we want to search the substring. In the while loop, we find the substring, assign the index of next occurrence to fromIndex and check if the returned value is greater than -1. The indexOf method returns -1 if the substring is not found in the string, otherwise, it returns the index of the substring.

Читайте также:  При наведении бордер css

Inside the while loop, we increment the count of occurrence of substring. We also increment the fromIndex by 1. That is because when we find the substring, next time we want to search the substring after that index. If we don’t do that, we will end up with an infinite loop.

2) Using the split method

You can use the split method as given below to count the substrings.

The split method returns an array of matching string parts. So basically we are splitting a string with the substring we want to find and checking how many array elements it has returned.

Important Note: The split method accepts regular expression. While using the above approach, beware of the regular expression metacharacters (characters which have special meaning in regular expression). Consider below given example.

Surprising result? We do not have “C++” in our string yet our program says it has found it 1 time. That is because the “+” sign has a special meaning in the regular expression and it means “one or more”. We do have “C” one or more times so searching “C++” returns 1. In order to avoid such errors, always use the quote method of Pattern class whenever you want to do a literal search using split method as given below.

Please check out string split example for more details.

3) Using the Apache Commons library

If you are using the Apache Commons library, you can use the countMatches method of the StringUtils class to count occurrences of a substring in the string as given below.

Источник

Find and count occurrences of substring in string in java

Find and count occurences of substring in String in Java

The indexOf() method in java is a specialized function to find the index of the first occurrence of a substring in a string. This method has 4 overloads.

We will use the second overload as we have to check the entire string. The fromIndex parameter is used to specify the starting index from where to start the search. This method returns an integer value indicating the position of the occurrence. If it returns -1, then it means that there exists no occurrence in the given string.

Further reading:

Count occurrences of Character in String in Java
Count number of words in a String

Using regular expression

The regular expression uses a specific syntax or pattern for matching text. We can use a regular expression to match the pattern of our substring and find its occurrences in the given string. In Java, we use the Pattern and Matcher class of regular expression to find the pattern and then match it. It is one of the simplest ways to find the number of occurrences of a substring in a string.

We have found the occurrences of the substring in the given string using the find() method of the Matcher class. After finding the occurrences, we have counted them by incrementing the count variable.

Using split() method

The split() method in java is used to split a string based on some substring. We will simply use this method with a little logic to find the number of occurrences of a substring in a string. We know that if there exists one pattern of a substring in the given string, then the method will divide the given string into two parts. Using this logic, we will find the length of the array of strings produced as a result of the split() method and subtract 1 from it to find the number of occurrences.

Источник

Java — Counting Substring Occurrences In A String

Twitter Facebook Google Pinterest

A quick guide to count the substring occurrences or frequency in a String in Java.

1. Overview

In this tutorial, We’ll learn how to find the count of substring present in the input string in java.

Java - Counting Substring Occurrences In A String

2. Java — Counting Substring Occurrences In A String using indexOf()

package com.javaprogramto.programs.strings.substring.count; public class SubstringCountExample < public static void main(String[] args) < int count = countSubStringInString("222", "22"); System.out.println(count); count = countSubStringInString("madam", "ma"); System.out.println(count); >public static int countSubStringInString(String string, String toFind) < int position = 0; int count = 0; while ((position = string.indexOf(toFind, position)) != -1) < position = position + 1; count++; >return count; > >

3. Java — Counting Substring Occurrences In A String using Pattern and Match

package com.javaprogramto.programs.strings.substring.count; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SubstringCountExample2 < public static void main(String[] args) < int count = countSubStringInString("222", "22"); System.out.println(count); count = countSubStringInString("madam", "ma"); System.out.println(count); >public static int countSubStringInString(String string, String toFind) < Pattern pattern = Pattern.compile(Pattern.quote(toFind)); Matcher matcher = pattern.matcher(string); int position = 0; int count = 0; while (matcher.find(position)) < position = matcher.start() + 1; count++; >return count; > >

4. Java — Counting Substring Occurrences In A String Using While Loop and charAt()

package com.javaprogramto.programs.strings.substring.count; public class SubstringCountExample3 < public static void main(String[] args) < int count = countSubStringInString("22222", "22"); System.out.println(count); count = countSubStringInString("madam", "ma"); System.out.println(count); >public static int countSubStringInString(String string, String toFind) < int M = toFind.length(); int N = string.length(); int res = 0; for (int i = 0; i > if (j == M) < res++; j = 0; >> return res; > >

5. Conclusion

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content

Источник

Оцените статью