• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

to count the no. of times a character occurs in a string

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
Can you tell me how to write a program to count the no. of times a character "a" occurs in the name "guruprasad" or any other string data which could be entered in the command line? I need the code and not the verbal explnation.
I am a beginner in java pl. encourage me.
Regards,
Guru
Send mail to gurumysore1@yahoo.com
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Guru,
Try the following.

Enjoy,
Manfred.
 
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From me, you're going to get part code, part verbal explanation.
If the strings being searched are short, the easiest way to do it would be to compare each character in the string with the letter you're looking for in a loop. Each time there is a match, increment a counter.
If you look at the API for String, you'll see two methods:
String.length() -- gets the length of the string
String.charAt(int) -- returns a specific char from the String
So, what you do is first get the length of the string passed in off the command line (let's call it myString):
int len = myString.length();
This is how long you want the loop to run. If your counter is:
int myCounter = 0;
and your char that was passed in by the user is called myChar then the search loop would look like:

And that chould do it. It's not a complete program, but there's not much left to do.

Originally posted by guru mysore:
Hi All,
Can you tell me how to write a program to count the no. of times a character "a" occurs in the name "guruprasad" or any other string data which could be entered in the command line? I need the code and not the verbal explnation.
I am a beginner in java pl. encourage me.
Regards,
Guru
Send mail to gurumysore1@yahoo.com


reply
    Bookmark Topic Watch Topic
  • New Topic