• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Search count in String Input

 
Ranch Hand
Posts: 205
Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I have a input in program as string "I am in america. am in". Here we notice that "am" and "in" words appears twice. So I want my output as below

I--1
am--2
in--2
america--1

So i tried below code..Here my first system.out.println just prints matched words like "am" and "in" not others. Please let me know where am i going wrong.

>
 
lowercase baba
Posts: 13070
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
look at where your System.out.println statement is. it's inside the block where you check to see if two strings are equal. since no string ever matches 'america', you will never print anything out for the 'america' string.

for fun, try changing your input string to "I am in america. am in am".

you'll get even stranger results....

you don't want to print out the count as soon as you find a match, since you might find more than one match (as the above suggested string illustrates).

You need to keep a counter for each word you find. Personally, i'd suggest using a map with the word as the key, and an int counter as the value.
 
A feeble attempt to tell you about our stuff that makes us money
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic