Get
the number of occurrences of a sub string in the given string.
StringUtilTest.java
As
you see above image string “ab” is repeated twice in “abrakadabra”.
Procedure
Step 1: Let
sourceString=”abrakadabra”, substring=”ab”
Step 2: Start from the 0th
index of the source string and search for the substring “ab”, if you do not
find any sib string, then there are 0 occurrences. If you found a sub string,
then start from the index (where the substring is located in the sourceString)
+ substring.legth() in sourceString.
Repeat
this procedure until end of the string.
Find
the below working application.
StringUtil.java
package com.sample.utils; public class StringUtil { /** * It return the number of occurrences of <code>subString</code> in the * <code>sourceString</code> * * @param sourceString * @param subString * @return */ public static int noOfOccurrences(String sourceString, String subString) { if (sourceString == null || subString == null || subString.isEmpty() || sourceString.isEmpty() || (subString.length() > sourceString.length())) { return -1; } int index = 0; int noOfTimes = 0; int fromIndex = 0; while ((index = sourceString.indexOf(subString, fromIndex)) != -1) { noOfTimes++; fromIndex = index + subString.length(); } return noOfTimes; } }
StringUtilTest.java
package com.sample.util; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.sample.utils.StringUtil; public class StringUtilTest { private String sourceString = null; private String subString = null; private int noOfOccurrences = -1; @Test public void noOfOccurrences_nullSourceAndnullSubString_negative1() { noOfOccurrences = StringUtil.noOfOccurrences(null, null); assertEquals(noOfOccurrences, -1); } @Test public void noOfOccurrences_nullSourceAndEmptySubString_negative1() { noOfOccurrences = StringUtil.noOfOccurrences(null, ""); assertEquals(noOfOccurrences, -1); } @Test public void noOfOccurrences_emptySourceAndNullSubString_negative1() { noOfOccurrences = StringUtil.noOfOccurrences("", null); assertEquals(noOfOccurrences, -1); } @Test public void noOfOccurrences_emptySourceAndEmptySubString_negative1() { noOfOccurrences = StringUtil.noOfOccurrences("", ""); assertEquals(noOfOccurrences, -1); } @Test public void noOfOccurrences_sourceStringAndSubString_negative1() { sourceString = "abrakadabra"; subString = "ab"; noOfOccurrences = StringUtil.noOfOccurrences(sourceString, subString); assertEquals(noOfOccurrences, 2); } }
You may like
Convert integers into roman equivalents
No comments:
Post a Comment