473,785 Members | 2,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using indexOf to count the number of times a letter occurrs?

evilmonkey
14 New Member
Is there a way to use index of in java to pull the number of occurrences of every letter in a user defined sentence? I can brute force this but is there a faster more elegant way to achieve the same result. I've started to try this but not sure I am on the right track. any help or push in the right direction would be appreciated.

Expand|Select|Wrap|Line Numbers
  1. import java.util.StringTokenizer;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class Main {
  6.  
  7.  public static void main(String[] args) {
  8.  
  9.  
  10.   System.out.println("Enter the sentence :");
  11.  
  12.   alphaCount alpha =new alphaCount(); 
  13.   Scanner input = new Scanner(System.in);
  14.   String output = "";
  15.   String sentence = input.nextLine();
  16.   StringTokenizer token = new StringTokenizer (sentence );
  17.  
  18.   //String[] words = sentence.split(" "); 
  19.   System.out.println("Number of A's is :"+sentence.indexOf('a'));
  20.   //System.out.println("Number of B's is :"+alpha.numOfBs(sentence));
  21.  }
  22.  
  23. }
  24.  
  25. public class alphaCount {
  26.  
  27.  
  28.     /** Creates a new instance of alphaCount */
  29.     public alphaCount() {
  30.     }
  31.  
  32.   // I could brute force each letter of the alphabet like this 
  33.  public static int numOfAs(String str) {
  34.  int numA = 0;
  35.  
  36.   for(int i = 0;i < str.length();i++) {
  37.    if(str.charAt(i) == 'a') {
  38.     numA++;
  39.    }
  40.  
  41.   }
  42.   return numA;
  43.  }
  44.  
  45.  public static int numOfBs(String str) {
  46.   int numB =0;
  47.  
  48.   for(int i = 0;i < str.length();i++) {
  49.    if(str.charAt(i) == 'b') {
  50.     numB++;
  51.    }
  52.  
  53.   }
  54.   return numB;
  55.  }
  56.  
  57.  
  58.     }
Feb 21 '07 #1
4 13884
Ganon11
3,652 Recognized Expert Specialist
You could define a method, numOfChars, that takes a character as its parameter and returns the amount of that character in the string. Thus, you could use sentence.numOfC hars('a'); to find the number of a's, sentence.numOfC hars('G'); for G's, and so on.
Feb 21 '07 #2
r035198x
13,262 MVP
Is there a way to use index of in java to pull the number of occurrences of every letter in a user defined sentence? I can brute force this but is there a faster more elegant way to achieve the same result. I've started to try this but not sure I am on the right track. any help or push in the right direction would be appreciated.

Expand|Select|Wrap|Line Numbers
  1. import java.util.StringTokenizer;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8.  
  9.  
  10. System.out.println("Enter the sentence :");
  11.  
  12. alphaCount alpha =new alphaCount(); 
  13. Scanner input = new Scanner(System.in);
  14. String output = "";
  15. String sentence = input.nextLine();
  16. StringTokenizer token = new StringTokenizer (sentence );
  17.  
  18. //String[] words = sentence.split(" "); 
  19. System.out.println("Number of A's is :"+sentence.indexOf('a'));
  20. //System.out.println("Number of B's is :"+alpha.numOfBs(sentence));
  21. }
  22.  
  23. }
  24.  
  25. public class alphaCount {
  26.  
  27.  
  28. /** Creates a new instance of alphaCount */
  29. public alphaCount() {
  30. }
  31.  
  32. // I could brute force each letter of the alphabet like this 
  33. public static int numOfAs(String str) {
  34. int numA = 0;
  35.  
  36. for(int i = 0;i < str.length();i++) {
  37. if(str.charAt(i) == 'a') {
  38.     numA++;
  39. }
  40.  
  41. }
  42. return numA;
  43. }
  44.  
  45. public static int numOfBs(String str) {
  46. int numB =0;
  47.  
  48. for(int i = 0;i < str.length();i++) {
  49. if(str.charAt(i) == 'b') {
  50.     numB++;
  51. }
  52.  
  53. }
  54. return numB;
  55. }
  56.  
  57.  
  58. }
Might want to have a read at regular expressions as well.
Feb 22 '07 #3
bloid
1 New Member
Did you mean something like:
Expand|Select|Wrap|Line Numbers
  1. String str = "Hello there!!" ;
  2. char ch = 'e' ;
  3. int count = 0 ;
  4. int pos = -1 ;
  5. while( ( pos = str.indexOf( ch, pos + 1 ) ) > -1 ) count++ ;
  6. System.out.println( "The character " + ch + " occurs " + count + " times" ) ;
?
Feb 22 '07 #4
evilmonkey
14 New Member
Did you mean something like:
Expand|Select|Wrap|Line Numbers
  1. String str = "Hello there!!" ;
  2. char ch = 'e' ;
  3. int count = 0 ;
  4. int pos = -1 ;
  5. while( ( pos = str.indexOf( ch, pos + 1 ) ) > -1 ) count++ ;
  6. System.out.println( "The character " + ch + " occurs " + count + " times" ) ;
?
Yes I did, but I actually figured it out and it is working, that was close to what I got.
thank you for the reply
Feb 22 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
4024
by: Phil Powell | last post by:
Relevancy scores are normally defined by a MySQL query on a table that has a fulltext index. The rules for relevancy scoring will exclude certain words due to their being too short (minimum default is 4 letters). This is the Fed. Everything is a TLA (three-letter acronym). Therefore, since I'm building a PORTABLE web application, changing MySQL's default settings for fulltext index querying is completely undoable and unrealistic, so...
5
7652
by: jester.dev | last post by:
Hello, I'm learning Python from Python Bible, and having some problems with this code below. When I run it, I get nothing. It should open the file poem.txt (which exists in the current directory) and count number of times any given word appears in the text. #!/usr/bin/python
4
2717
by: Japhy | last post by:
Hello, I'm am pulling data from a mysql db and want to use the data to populate a <ul. Here are relavent parts of my code : $wohdate = mysql_result($wohRS,$wohndx,woh_date); $woh_display .="<li>".$wohdate."</li>" ; $TemplateText = Replace($TemplateText,"@$wohdisplayndx@",$woh_display);
11
6601
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on where the job is running, the job runs sucessfully, PDF files got generated, everything is good. If I scheduled the job to run at the time that I am not logged into the server, Access is not able to print to the printer. The error is pretty...
1
4010
by: Daveyk0 | last post by:
Hello there, I have a front end database that I have recently made very many changes to to allow off-line use. I keep copies of the databases on my hard drive and link to them rather than the live databases on the network. Is there a way, via code, when I get back in-house from being on the road to click a button, and select the backends I want to link to? I would want to delete all the current links and link to the "live"
1
6428
by: ratnakarp | last post by:
Hi, I have a search text box. The user enters the value in the text box and click on enter button. In code behind on button click i'm writing the code to get the values from the database and binding it to a repeater control. This repeater control has multiple text boxes and buttons. Can you please tell me how can i do paging in this case ? I'm posting my code below. The problem is that if i click on "AdjustThisAd" button, it opens...
6
17205
by: ransoma22 | last post by:
I developing an application that receive SMS from a connected GSM handphone, e.g Siemens M55, Nokia 6230,etc through the data cable. The application(VB.NET) will receive the SMS automatically, process and output to the screen in my application when a message arrived. But the problem is how do I read the SMS message immediately when it arrived without my handphone BeEPINg for new message ? I read up the AT commands, but when getting down...
4
2280
by: onecorp | last post by:
I have a SQL table comprised of 31 columns. The first column is simply an id column, the next 30 columns are labelled ,.... The numerical columns have a tinyint type and the data stored is either 1 or null. I wish to count the number of times a one appears in one column simultaneously with another column: eg count the number of times 1 appears in column and 1 also appears in column in the same row:
5
5716
by: isabelle | last post by:
hi, every body.. I have two program I couldn’t solve them So, can any body help me. please!! 1-Write a program that accepts a character and count number of occurrences in a file. The file should have some text, and the program count how many times the inputted character repeated in the file and prints the result on the screen. (Hint: you have to use continue statement in your solution ) Sample input:
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9485
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10356
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9958
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5390
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4058
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3662
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2890
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.