How to find a substring in a string and get its count using java











up vote
-1
down vote

favorite












I have been given a problem where I need to find the substring in a char array and have to count how many times that substring occurred.
For eg: "aabbcccddaabbbccc"
O/P:
aa:2
bb:1
ccc:2
dd:1
bbb:1



I tried this code but it is not giving me proper solution, if someone could suggest me what I am doing wrong



public class CountSubString {
static Set set=new HashSet<>();
static List list=new ArrayList<>();


private static Map<char, Integer> count(char charArrayToParse){
Map<char, Integer> subString = new HashMap<char, Integer>();

for (int i=0; i<charArrayToParse.length ;)
{StringBuilder word= new StringBuilder();
for (int j=i; j<charArrayToParse.length; j++) {

if(charArrayToParse[i] == charArrayToParse[j]) {
word.append(charArrayToParse[j]);
}
else {
char subStringDone = word.toString().toCharArray();
if(subString.isEmpty())
subString.put(subStringDone, 1);

else if(subString.containsKey(subStringDone)) {
subString.put(subStringDone, subString.get(subStringDone)+1);
}
else {
subString.put(subStringDone, 1);
}

//System.out.println("Word value are"+subString.get(key));
i=j;
break;
}

}

}
Set<char> keyValues= subString.keySet();
for(char ch : keyValues) {
if(subString.get(ch)>1) {
System.out.println(ch+"--->"+subString.get(ch));
}
}
return subString;
}
public static void main(String args) {
// TODO Auto-generated method stub
String str = "aaabbbccddddaaaeebbb";
char charArray = str.toCharArray();
Map<char, Integer> parsedArray= new HashMap<char, Integer>();
parsedArray= count(charArray);
}

}









share|improve this question






















  • right now you have infinite loop, because you are not incrementing your i in for...
    – Schidu Luca
    Nov 9 at 13:22










  • is bb=1 or bb=3?
    – hunter
    Nov 9 at 13:25

















up vote
-1
down vote

favorite












I have been given a problem where I need to find the substring in a char array and have to count how many times that substring occurred.
For eg: "aabbcccddaabbbccc"
O/P:
aa:2
bb:1
ccc:2
dd:1
bbb:1



I tried this code but it is not giving me proper solution, if someone could suggest me what I am doing wrong



public class CountSubString {
static Set set=new HashSet<>();
static List list=new ArrayList<>();


private static Map<char, Integer> count(char charArrayToParse){
Map<char, Integer> subString = new HashMap<char, Integer>();

for (int i=0; i<charArrayToParse.length ;)
{StringBuilder word= new StringBuilder();
for (int j=i; j<charArrayToParse.length; j++) {

if(charArrayToParse[i] == charArrayToParse[j]) {
word.append(charArrayToParse[j]);
}
else {
char subStringDone = word.toString().toCharArray();
if(subString.isEmpty())
subString.put(subStringDone, 1);

else if(subString.containsKey(subStringDone)) {
subString.put(subStringDone, subString.get(subStringDone)+1);
}
else {
subString.put(subStringDone, 1);
}

//System.out.println("Word value are"+subString.get(key));
i=j;
break;
}

}

}
Set<char> keyValues= subString.keySet();
for(char ch : keyValues) {
if(subString.get(ch)>1) {
System.out.println(ch+"--->"+subString.get(ch));
}
}
return subString;
}
public static void main(String args) {
// TODO Auto-generated method stub
String str = "aaabbbccddddaaaeebbb";
char charArray = str.toCharArray();
Map<char, Integer> parsedArray= new HashMap<char, Integer>();
parsedArray= count(charArray);
}

}









share|improve this question






















  • right now you have infinite loop, because you are not incrementing your i in for...
    – Schidu Luca
    Nov 9 at 13:22










  • is bb=1 or bb=3?
    – hunter
    Nov 9 at 13:25















up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I have been given a problem where I need to find the substring in a char array and have to count how many times that substring occurred.
For eg: "aabbcccddaabbbccc"
O/P:
aa:2
bb:1
ccc:2
dd:1
bbb:1



I tried this code but it is not giving me proper solution, if someone could suggest me what I am doing wrong



public class CountSubString {
static Set set=new HashSet<>();
static List list=new ArrayList<>();


private static Map<char, Integer> count(char charArrayToParse){
Map<char, Integer> subString = new HashMap<char, Integer>();

for (int i=0; i<charArrayToParse.length ;)
{StringBuilder word= new StringBuilder();
for (int j=i; j<charArrayToParse.length; j++) {

if(charArrayToParse[i] == charArrayToParse[j]) {
word.append(charArrayToParse[j]);
}
else {
char subStringDone = word.toString().toCharArray();
if(subString.isEmpty())
subString.put(subStringDone, 1);

else if(subString.containsKey(subStringDone)) {
subString.put(subStringDone, subString.get(subStringDone)+1);
}
else {
subString.put(subStringDone, 1);
}

//System.out.println("Word value are"+subString.get(key));
i=j;
break;
}

}

}
Set<char> keyValues= subString.keySet();
for(char ch : keyValues) {
if(subString.get(ch)>1) {
System.out.println(ch+"--->"+subString.get(ch));
}
}
return subString;
}
public static void main(String args) {
// TODO Auto-generated method stub
String str = "aaabbbccddddaaaeebbb";
char charArray = str.toCharArray();
Map<char, Integer> parsedArray= new HashMap<char, Integer>();
parsedArray= count(charArray);
}

}









share|improve this question













I have been given a problem where I need to find the substring in a char array and have to count how many times that substring occurred.
For eg: "aabbcccddaabbbccc"
O/P:
aa:2
bb:1
ccc:2
dd:1
bbb:1



I tried this code but it is not giving me proper solution, if someone could suggest me what I am doing wrong



public class CountSubString {
static Set set=new HashSet<>();
static List list=new ArrayList<>();


private static Map<char, Integer> count(char charArrayToParse){
Map<char, Integer> subString = new HashMap<char, Integer>();

for (int i=0; i<charArrayToParse.length ;)
{StringBuilder word= new StringBuilder();
for (int j=i; j<charArrayToParse.length; j++) {

if(charArrayToParse[i] == charArrayToParse[j]) {
word.append(charArrayToParse[j]);
}
else {
char subStringDone = word.toString().toCharArray();
if(subString.isEmpty())
subString.put(subStringDone, 1);

else if(subString.containsKey(subStringDone)) {
subString.put(subStringDone, subString.get(subStringDone)+1);
}
else {
subString.put(subStringDone, 1);
}

//System.out.println("Word value are"+subString.get(key));
i=j;
break;
}

}

}
Set<char> keyValues= subString.keySet();
for(char ch : keyValues) {
if(subString.get(ch)>1) {
System.out.println(ch+"--->"+subString.get(ch));
}
}
return subString;
}
public static void main(String args) {
// TODO Auto-generated method stub
String str = "aaabbbccddddaaaeebbb";
char charArray = str.toCharArray();
Map<char, Integer> parsedArray= new HashMap<char, Integer>();
parsedArray= count(charArray);
}

}






java string hashmap






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 9 at 13:12









Developer52

204417




204417












  • right now you have infinite loop, because you are not incrementing your i in for...
    – Schidu Luca
    Nov 9 at 13:22










  • is bb=1 or bb=3?
    – hunter
    Nov 9 at 13:25




















  • right now you have infinite loop, because you are not incrementing your i in for...
    – Schidu Luca
    Nov 9 at 13:22










  • is bb=1 or bb=3?
    – hunter
    Nov 9 at 13:25


















right now you have infinite loop, because you are not incrementing your i in for...
– Schidu Luca
Nov 9 at 13:22




right now you have infinite loop, because you are not incrementing your i in for...
– Schidu Luca
Nov 9 at 13:22












is bb=1 or bb=3?
– hunter
Nov 9 at 13:25






is bb=1 or bb=3?
– hunter
Nov 9 at 13:25














3 Answers
3






active

oldest

votes

















up vote
1
down vote













Since this looks like a homework assignment, I'm not going to post a code solution, but I'll point you in the right direction.



Your double for loop is creating an infinite loop. You're setting i = j and it's not getting set high enough to break out of the loop (never goes past 17). Nested for loops in my book are usually a code smell, you've got something that should be broken into a few more functions (low cohesion).



In this case, your first function should be to break your string down into patterns. Your nested for loops can be reduced down to a single loop, and each time a pattern is found, add it to a Set<String> instead of a map. This will prevent duplicates since a Set can only contain unique values.



You can then move on to the next part which is to figure out your pattern counts. Remember, in that case iterate over the string and check for matches. You'll need to take into account that aa will also match aaa when doing your counts.






share|improve this answer





















  • Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
    – Developer52
    Nov 10 at 6:57










  • I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
    – Jason Armstrong
    Nov 10 at 12:46










  • I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
    – Developer52
    Nov 10 at 13:13












  • Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
    – Jason Armstrong
    Nov 10 at 13:35


















up vote
0
down vote













Can you use libraries? If so there's StringUtils in the apache.commons.lang3 that can solve the problem in a single line like this:



int count = StringUtils.countMatches("aabbcccddaabbbccc", "aa");





share|improve this answer





















  • But I have to find all the substring and it's count, not only aa
    – Developer52
    Nov 10 at 6:27


















up vote
0
down vote













Something to consider.. for bbaaarr are there two sequences of aa or just one? My solution considers that there are two but it can be easily adjusted for the other case.



Comments in my code to help explain it:





/**
* Returns the number of times the sequence occurs in the string.
* @param seq - the sequence you are looking for
* @param str - the string you are searching in
*/
private static int count(String seq, String str) {
if(seq == null || seq.isEmpty() ||
str == null || str.isEmpty() ){
return 0;
}
int count = 0;

// the first character of the sequence you are looking for
final char seqChar = seq.charAt(0);

// if there aren't seq.length() chars remaining then
// it's no longer possible to match your sequence
// so this is the max index to go to when looking for it
final int maxIndex = str.length() - seq.length();

// iterate through the characters in your string
for (int i = 0; i <= maxIndex; i++) {
// when you find a character matching the start of your sequence
// then compare the substring of equal length to your sequence
// and if it matches then you have a match
if (seqChar == str.charAt(i) &&
seq.equals(str.substring(i, i + seq.length()))) {
count++;
}
}
return count;
}




public static void main(String args){
String s = "aabbcccddaabbbccc";
System.out.println(count("aa", s)); // 2
// [aa]bbcccddaabbbccc
// aabbcccdd[aa]bbbccc

System.out.println(count("bb", s)); // 3
// aa[bb]cccddaabbbccc
// aabbcccddaa[bb]bccc
// aabbcccddaab[bbccc

System.out.println(count("cc", s)); // 4
// aabb[cc]cddaabbbccc
// aabbc[cc]ddaabbbccc
// aabbcccddaabbb[cc]c
// aabbcccddaabbbc[cc]
}





share|improve this answer























  • Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
    – Developer52
    Nov 10 at 6:54











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53226370%2fhow-to-find-a-substring-in-a-string-and-get-its-count-using-java%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote













Since this looks like a homework assignment, I'm not going to post a code solution, but I'll point you in the right direction.



Your double for loop is creating an infinite loop. You're setting i = j and it's not getting set high enough to break out of the loop (never goes past 17). Nested for loops in my book are usually a code smell, you've got something that should be broken into a few more functions (low cohesion).



In this case, your first function should be to break your string down into patterns. Your nested for loops can be reduced down to a single loop, and each time a pattern is found, add it to a Set<String> instead of a map. This will prevent duplicates since a Set can only contain unique values.



You can then move on to the next part which is to figure out your pattern counts. Remember, in that case iterate over the string and check for matches. You'll need to take into account that aa will also match aaa when doing your counts.






share|improve this answer





















  • Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
    – Developer52
    Nov 10 at 6:57










  • I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
    – Jason Armstrong
    Nov 10 at 12:46










  • I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
    – Developer52
    Nov 10 at 13:13












  • Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
    – Jason Armstrong
    Nov 10 at 13:35















up vote
1
down vote













Since this looks like a homework assignment, I'm not going to post a code solution, but I'll point you in the right direction.



Your double for loop is creating an infinite loop. You're setting i = j and it's not getting set high enough to break out of the loop (never goes past 17). Nested for loops in my book are usually a code smell, you've got something that should be broken into a few more functions (low cohesion).



In this case, your first function should be to break your string down into patterns. Your nested for loops can be reduced down to a single loop, and each time a pattern is found, add it to a Set<String> instead of a map. This will prevent duplicates since a Set can only contain unique values.



You can then move on to the next part which is to figure out your pattern counts. Remember, in that case iterate over the string and check for matches. You'll need to take into account that aa will also match aaa when doing your counts.






share|improve this answer





















  • Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
    – Developer52
    Nov 10 at 6:57










  • I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
    – Jason Armstrong
    Nov 10 at 12:46










  • I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
    – Developer52
    Nov 10 at 13:13












  • Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
    – Jason Armstrong
    Nov 10 at 13:35













up vote
1
down vote










up vote
1
down vote









Since this looks like a homework assignment, I'm not going to post a code solution, but I'll point you in the right direction.



Your double for loop is creating an infinite loop. You're setting i = j and it's not getting set high enough to break out of the loop (never goes past 17). Nested for loops in my book are usually a code smell, you've got something that should be broken into a few more functions (low cohesion).



In this case, your first function should be to break your string down into patterns. Your nested for loops can be reduced down to a single loop, and each time a pattern is found, add it to a Set<String> instead of a map. This will prevent duplicates since a Set can only contain unique values.



You can then move on to the next part which is to figure out your pattern counts. Remember, in that case iterate over the string and check for matches. You'll need to take into account that aa will also match aaa when doing your counts.






share|improve this answer












Since this looks like a homework assignment, I'm not going to post a code solution, but I'll point you in the right direction.



Your double for loop is creating an infinite loop. You're setting i = j and it's not getting set high enough to break out of the loop (never goes past 17). Nested for loops in my book are usually a code smell, you've got something that should be broken into a few more functions (low cohesion).



In this case, your first function should be to break your string down into patterns. Your nested for loops can be reduced down to a single loop, and each time a pattern is found, add it to a Set<String> instead of a map. This will prevent duplicates since a Set can only contain unique values.



You can then move on to the next part which is to figure out your pattern counts. Remember, in that case iterate over the string and check for matches. You'll need to take into account that aa will also match aaa when doing your counts.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 9 at 13:37









Jason Armstrong

652313




652313












  • Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
    – Developer52
    Nov 10 at 6:57










  • I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
    – Jason Armstrong
    Nov 10 at 12:46










  • I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
    – Developer52
    Nov 10 at 13:13












  • Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
    – Jason Armstrong
    Nov 10 at 13:35


















  • Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
    – Developer52
    Nov 10 at 6:57










  • I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
    – Jason Armstrong
    Nov 10 at 12:46










  • I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
    – Developer52
    Nov 10 at 13:13












  • Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
    – Jason Armstrong
    Nov 10 at 13:35
















Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
– Developer52
Nov 10 at 6:57




Thank you for your direction, but I am not getting how to reduce it to one loop as the problem I am facing is I need to match characters before breaking it into possible substrings.. Can you please suggest me a generic way for achieving this.. It is not a assignment it was asked in a interview so am trying to crack this..
– Developer52
Nov 10 at 6:57












I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
– Jason Armstrong
Nov 10 at 12:46




I'd decompose your current method into two separate methods: Set<String> parseKeys(String input) and Map<String, int> countMatches(String input, Set<String> keys) The first method iterates the string, and you compare the current letter to the previous letter. If they're different, or the end of the array is reached, you add that sequence to the set. Since sets enforce uniqueness, you'll have substrings. Your second method then takes those unique substrings (keys) and counts the times it appears in the input string.
– Jason Armstrong
Nov 10 at 12:46












I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
– Developer52
Nov 10 at 13:13






I am not getting the way of how to compare the current letter and the previous letter without using two loops.. One more scenario is I have to match both the current indexes too as I have to add both the characters to substring if they are same.. For eg: aaabbbccc now here I have to add all the three a's so I have to add the current index as well as the next index too.
– Developer52
Nov 10 at 13:13














Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
– Jason Armstrong
Nov 10 at 13:35




Try a local variable declared outside the for loop. Something along the lines of char previousLetter, update it inside of the for loop. Try some code, and share it.
– Jason Armstrong
Nov 10 at 13:35












up vote
0
down vote













Can you use libraries? If so there's StringUtils in the apache.commons.lang3 that can solve the problem in a single line like this:



int count = StringUtils.countMatches("aabbcccddaabbbccc", "aa");





share|improve this answer





















  • But I have to find all the substring and it's count, not only aa
    – Developer52
    Nov 10 at 6:27















up vote
0
down vote













Can you use libraries? If so there's StringUtils in the apache.commons.lang3 that can solve the problem in a single line like this:



int count = StringUtils.countMatches("aabbcccddaabbbccc", "aa");





share|improve this answer





















  • But I have to find all the substring and it's count, not only aa
    – Developer52
    Nov 10 at 6:27













up vote
0
down vote










up vote
0
down vote









Can you use libraries? If so there's StringUtils in the apache.commons.lang3 that can solve the problem in a single line like this:



int count = StringUtils.countMatches("aabbcccddaabbbccc", "aa");





share|improve this answer












Can you use libraries? If so there's StringUtils in the apache.commons.lang3 that can solve the problem in a single line like this:



int count = StringUtils.countMatches("aabbcccddaabbbccc", "aa");






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 9 at 13:24









Amongalen

1529




1529












  • But I have to find all the substring and it's count, not only aa
    – Developer52
    Nov 10 at 6:27


















  • But I have to find all the substring and it's count, not only aa
    – Developer52
    Nov 10 at 6:27
















But I have to find all the substring and it's count, not only aa
– Developer52
Nov 10 at 6:27




But I have to find all the substring and it's count, not only aa
– Developer52
Nov 10 at 6:27










up vote
0
down vote













Something to consider.. for bbaaarr are there two sequences of aa or just one? My solution considers that there are two but it can be easily adjusted for the other case.



Comments in my code to help explain it:





/**
* Returns the number of times the sequence occurs in the string.
* @param seq - the sequence you are looking for
* @param str - the string you are searching in
*/
private static int count(String seq, String str) {
if(seq == null || seq.isEmpty() ||
str == null || str.isEmpty() ){
return 0;
}
int count = 0;

// the first character of the sequence you are looking for
final char seqChar = seq.charAt(0);

// if there aren't seq.length() chars remaining then
// it's no longer possible to match your sequence
// so this is the max index to go to when looking for it
final int maxIndex = str.length() - seq.length();

// iterate through the characters in your string
for (int i = 0; i <= maxIndex; i++) {
// when you find a character matching the start of your sequence
// then compare the substring of equal length to your sequence
// and if it matches then you have a match
if (seqChar == str.charAt(i) &&
seq.equals(str.substring(i, i + seq.length()))) {
count++;
}
}
return count;
}




public static void main(String args){
String s = "aabbcccddaabbbccc";
System.out.println(count("aa", s)); // 2
// [aa]bbcccddaabbbccc
// aabbcccdd[aa]bbbccc

System.out.println(count("bb", s)); // 3
// aa[bb]cccddaabbbccc
// aabbcccddaa[bb]bccc
// aabbcccddaab[bbccc

System.out.println(count("cc", s)); // 4
// aabb[cc]cddaabbbccc
// aabbc[cc]ddaabbbccc
// aabbcccddaabbb[cc]c
// aabbcccddaabbbc[cc]
}





share|improve this answer























  • Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
    – Developer52
    Nov 10 at 6:54















up vote
0
down vote













Something to consider.. for bbaaarr are there two sequences of aa or just one? My solution considers that there are two but it can be easily adjusted for the other case.



Comments in my code to help explain it:





/**
* Returns the number of times the sequence occurs in the string.
* @param seq - the sequence you are looking for
* @param str - the string you are searching in
*/
private static int count(String seq, String str) {
if(seq == null || seq.isEmpty() ||
str == null || str.isEmpty() ){
return 0;
}
int count = 0;

// the first character of the sequence you are looking for
final char seqChar = seq.charAt(0);

// if there aren't seq.length() chars remaining then
// it's no longer possible to match your sequence
// so this is the max index to go to when looking for it
final int maxIndex = str.length() - seq.length();

// iterate through the characters in your string
for (int i = 0; i <= maxIndex; i++) {
// when you find a character matching the start of your sequence
// then compare the substring of equal length to your sequence
// and if it matches then you have a match
if (seqChar == str.charAt(i) &&
seq.equals(str.substring(i, i + seq.length()))) {
count++;
}
}
return count;
}




public static void main(String args){
String s = "aabbcccddaabbbccc";
System.out.println(count("aa", s)); // 2
// [aa]bbcccddaabbbccc
// aabbcccdd[aa]bbbccc

System.out.println(count("bb", s)); // 3
// aa[bb]cccddaabbbccc
// aabbcccddaa[bb]bccc
// aabbcccddaab[bbccc

System.out.println(count("cc", s)); // 4
// aabb[cc]cddaabbbccc
// aabbc[cc]ddaabbbccc
// aabbcccddaabbb[cc]c
// aabbcccddaabbbc[cc]
}





share|improve this answer























  • Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
    – Developer52
    Nov 10 at 6:54













up vote
0
down vote










up vote
0
down vote









Something to consider.. for bbaaarr are there two sequences of aa or just one? My solution considers that there are two but it can be easily adjusted for the other case.



Comments in my code to help explain it:





/**
* Returns the number of times the sequence occurs in the string.
* @param seq - the sequence you are looking for
* @param str - the string you are searching in
*/
private static int count(String seq, String str) {
if(seq == null || seq.isEmpty() ||
str == null || str.isEmpty() ){
return 0;
}
int count = 0;

// the first character of the sequence you are looking for
final char seqChar = seq.charAt(0);

// if there aren't seq.length() chars remaining then
// it's no longer possible to match your sequence
// so this is the max index to go to when looking for it
final int maxIndex = str.length() - seq.length();

// iterate through the characters in your string
for (int i = 0; i <= maxIndex; i++) {
// when you find a character matching the start of your sequence
// then compare the substring of equal length to your sequence
// and if it matches then you have a match
if (seqChar == str.charAt(i) &&
seq.equals(str.substring(i, i + seq.length()))) {
count++;
}
}
return count;
}




public static void main(String args){
String s = "aabbcccddaabbbccc";
System.out.println(count("aa", s)); // 2
// [aa]bbcccddaabbbccc
// aabbcccdd[aa]bbbccc

System.out.println(count("bb", s)); // 3
// aa[bb]cccddaabbbccc
// aabbcccddaa[bb]bccc
// aabbcccddaab[bbccc

System.out.println(count("cc", s)); // 4
// aabb[cc]cddaabbbccc
// aabbc[cc]ddaabbbccc
// aabbcccddaabbb[cc]c
// aabbcccddaabbbc[cc]
}





share|improve this answer














Something to consider.. for bbaaarr are there two sequences of aa or just one? My solution considers that there are two but it can be easily adjusted for the other case.



Comments in my code to help explain it:





/**
* Returns the number of times the sequence occurs in the string.
* @param seq - the sequence you are looking for
* @param str - the string you are searching in
*/
private static int count(String seq, String str) {
if(seq == null || seq.isEmpty() ||
str == null || str.isEmpty() ){
return 0;
}
int count = 0;

// the first character of the sequence you are looking for
final char seqChar = seq.charAt(0);

// if there aren't seq.length() chars remaining then
// it's no longer possible to match your sequence
// so this is the max index to go to when looking for it
final int maxIndex = str.length() - seq.length();

// iterate through the characters in your string
for (int i = 0; i <= maxIndex; i++) {
// when you find a character matching the start of your sequence
// then compare the substring of equal length to your sequence
// and if it matches then you have a match
if (seqChar == str.charAt(i) &&
seq.equals(str.substring(i, i + seq.length()))) {
count++;
}
}
return count;
}




public static void main(String args){
String s = "aabbcccddaabbbccc";
System.out.println(count("aa", s)); // 2
// [aa]bbcccddaabbbccc
// aabbcccdd[aa]bbbccc

System.out.println(count("bb", s)); // 3
// aa[bb]cccddaabbbccc
// aabbcccddaa[bb]bccc
// aabbcccddaab[bbccc

System.out.println(count("cc", s)); // 4
// aabb[cc]cddaabbbccc
// aabbc[cc]ddaabbbccc
// aabbcccddaabbb[cc]c
// aabbcccddaabbbc[cc]
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 9 at 13:56

























answered Nov 9 at 13:29









xtratic

2,2401822




2,2401822












  • Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
    – Developer52
    Nov 10 at 6:54


















  • Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
    – Developer52
    Nov 10 at 6:54
















Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
– Developer52
Nov 10 at 6:54




Thank you for your code.. But here you have already taken the substring, but I am facing issues in finding substrings only from the array and also the string could be generic. So could you please suggest me a generic code to first find out its substring then its count
– Developer52
Nov 10 at 6:54


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53226370%2fhow-to-find-a-substring-in-a-string-and-get-its-count-using-java%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()