Win a copy of Learning Java by Building Android Games this week in the Android forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

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

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Hi Guru,
Try the following.

Enjoy,
Manfred.
 
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • 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


 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!