+ 1

Why this program is not working according to me as i want the occurenece of selective text with in a string

for e.g. take a string as javavava so we have to find the occurrence of av so the output come 3 as av come three time https://code.sololearn.com/cdwP3Gb9LR25/?ref=app Dan Walker Donna Sandeep Awasthi

6th Oct 2018, 4:35 PM
Harsh Agrawal
Harsh Agrawal - avatar
11 Respuestas
+ 2
change l2 = sub.length () instead of str.length()
6th Oct 2018, 6:06 PM
Suhail Pappu
Suhail Pappu - avatar
+ 19
Harsh Agrawal try this public class Program { public static void main(String[] args) { String a="javavavav"; String b="av"; String c="";int d=0; for(int i=0;i<a.length()-1;i++) { c=a.charAt(i)+""+a.charAt(i+1); if(c.equals(b)) { d++; } System.out.print(a.charAt(i)); } System.out.println(" "+d); } }
6th Oct 2018, 7:35 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 3
Harsh Agrawal my proposition public class Program { public static void main(String[] args) { String str="javavava"; String sub="av"; int l1= str.length(); int l2= sub.length(); str = str.replace(sub,""); System.out.println((l1-str.length())/l2); } }
6th Oct 2018, 11:06 PM
Michal
Michal - avatar
+ 2
Donna sorry, I'm not sure why substring is inappropriate, and why your code should work (and who is upvoting it...) In your code it only counts "a" and "v" but there's no need for them to be together, so if you put the target string as "jaaavvv" you will get the answer of 3 for occurrences of "av" which is not correct (at least to my understanding of the description, as well as this being a common beginner exercise) The OPs use of substring seems to be exactly what is required and making the suggested two-character change solves the issue...
7th Oct 2018, 4:18 AM
Dan Walker
Dan Walker - avatar
+ 1
line 7: try changing this to sub instead of str :p
6th Oct 2018, 4:51 PM
Dan Walker
Dan Walker - avatar
+ 1
thnxzzz all of u
7th Oct 2018, 12:05 AM
Harsh Agrawal
Harsh Agrawal - avatar
+ 1
7th Oct 2018, 4:36 AM
Harsh Agrawal
Harsh Agrawal - avatar
0
Donna it's not a problem, I just wasn't sure as it seemed overcomplicated for the issue I thought the OP was having. One should never code for constants :p the logic should be sound for the description of the problem :)
7th Oct 2018, 5:41 AM
Dan Walker
Dan Walker - avatar
0
hi donna i want to learn c language please help me please
23rd Oct 2018, 5:41 PM
Jamal Ahmad