Results 1 to 3 of 3
- 05-04-2008, 12:35 PM #1
Member
- Join Date
- Mar 2008
- Posts
- 31
- Rep Power
- 0
How To count the occurnces of astring in another string
Hello , How To count the occurnces of astring in another string I try This Code but the result is wrong help please
Java Code:public class Main { static Scanner console = new Scanner(System.in); public static void main(String[] args) { System.out.println("Enter Two stings "); System.out.println(); String str1 = console.nextLine(); String str2 = console.nextLine(); print (count (str1,str2 )); } public static int count (String x, String y) { int num = x.replaceAll(x ,y).length(); return(num); } public static void print (int b) { System.out.println("The Number of occrrunces is " +b); } }
- 05-04-2008, 05:22 PM #2
Just to confirm,
Can you show the example inputs and an output?freedom exists in the world of ideas
- 05-04-2008, 10:52 PM #3
Here is a classical implementation:
When you run it, it will display:Java Code:package javaforums; public class StringCount { public static void main(String[] args) { String source = "String having a lot of instances of the substring in"; String query = "in"; int occ = 0; int pos = source.indexOf(query); while (pos != -1) { System.out.println("Query string [" + query + "] found at index: " + pos); occ++; pos = source.indexOf(query, pos + query.length()); } System.out.println("Query string [" + query + "] found: " + occ + " times"); } }
You can adapt it to your requirements so you read the source and query strings from the console. Enjoy.Java Code:Query string [in] found at index: 3 Query string [in] found at index: 10 Query string [in] found at index: 23 Query string [in] found at index: 46 Query string [in] found at index: 50 Query string [in] found: 5 times
Daniel @ [www.littletutorials.com]
Language is froth on the surface of thought
Similar Threads
-
Select Count
By Apple2 in forum JavaServer Pages (JSP) and JSTLReplies: 1Last Post: 04-29-2008, 09:02 AM -
How to get the count of all the lines in a file
By Java Tip in forum java.ioReplies: 0Last Post: 04-06-2008, 07:45 PM -
Getting row count
By Java Tip in forum Java TipReplies: 0Last Post: 02-11-2008, 08:49 AM -
how to count 2 inserts together?
By kim85 in forum New To JavaReplies: 0Last Post: 01-20-2008, 11:25 AM -
Getting row count from executeQuery()
By Java Tip in forum Java TipReplies: 0Last Post: 12-05-2007, 02:31 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks