• Post Reply Bookmark Topic Watch Topic
  • New Topic

searching  RSS feed

 
Rauhl Roy
Ranch Hand
Posts: 401
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
May I know how to search a string and count matching words.




i want to count how many 'you's are there in the above String str.

 
Kshitij Chandrasen
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are simple ways that I can think of -
1. Split the string with the delimiter being the sub-string that you need to search for. You would get faulty result if your sub-string is overlapping each other. For ex-
String to search in - "theyforforfortheforforin"
Sub-string to search for - "forfor"
It depends on what your requirements are.

2. You can use regular expression to find the number of matching for a regex.
Read about it here - Java Regex Documentation for Regex


I'm sure there are many more methods, explore!
 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To approach this on the lines of a generic algorithm.

I would scan/read the line word by word. Then maintain a data structure which stores the word and the number of times it occurs. The logic would be :-

1. Read the next word in the sentence.
2. Check if the word is already present in the data structure.
3. If present then increment the count associated.
4. If not present add the word to the data structure with a count of '1'.
5. Continue the process if there are more words.

At the end of the loop/iteration you have a data structure that contains all the words and the number of times it occurs.

Cheers,
Raj.
 
Rauhl Roy
Ranch Hand
Posts: 401
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raj Kamal wrote:To approach this on the lines of a generic algorithm.

I would scan/read the line word by word. Then maintain a data structure which stores the word and the number of times it occurs. The logic would be :-

1. Read the next word in the sentence.
2. Check if the word is already present in the data structure.
3. If present then increment the count associated.
4. If not present add the word to the data structure with a count of '1'.
5. Continue the process if there are more words.

At the end of the loop/iteration you have a data structure that contains all the words and the number of times it occurs.

Cheers,
Raj.


May i know how would you read(code please)?
 
Campbell Ritchie
Marshal
Posts: 56534
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rauhl Roy wrote: . . . May i know how would you read(code please)?
I am afraid not. We don't give out code. We would like you to try and post what you have got, then we can see whether we agree with you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!