[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 339
  • Last Modified:

Counting # of occurrences of a character

hi all, I have the following codes.
This will tell me where the character (char1) is located. However, I am trying to find out how many times char1 has appeared in the sentence. For example: if sentence is "my name is", and char1 is 'm', then it will display 2.
I just can't figure out how to count using indexOf.
Anything helps is appreciated.

import java.util.Scanner;

public class Occur
{
      public static void main( String args[] )
      {
            int count = 0;
            Scanner scanner = new Scanner( System.in );
            System.out.println( "Enter a line of text:" );
            System.out.println();
            String sentence = scanner.nextLine();
            
            Scanner input = new Scanner( System.in );
            System.out.println( "\nEnter a search character:" );
            System.out.println();
            String char1 = input.nextLine();
            System.out.println();
            
            System.out.printf( "%s is located at index %d\n", char1, sentence .indexOf( char1 ) );

      }
}      
0
civicy2k
Asked:
civicy2k
  • 11
  • 4
  • 2
  • +1
1 Solution
 
aozarovCommented:
public class T
{
      public static void main(String st[])
      {
            System.out.println(count("my name", 'm', 0));
      }

      public static int count(String name, char ch, int from)
      {
            int index = name.indexOf(ch, from);
            if (index < 0)
                  return 0;
            else
                  return 1 + count(name, ch, index + 1);
      }
}

You can use the count method
0
 
JakobACommented:
you could use the  String.split method  it returns an array of strings with each cell holding all but the separator as many time as that happen in the string
eg:
     String[] resArr = "my name is".split("m");
     //  now resArr contain 0->""        // beginning to first "m"
     //                              1->"y na"  // between the "m"'s
     //                              2->"e is"   // last "m" to end
    int nrMs = resArr.length()-1;      // antal "m" i den streng    // one "m" less than nr of cells in the array

regards JakobA
0
 
aozarovCommented:
Just in case you don't like recursive methods:

public class T
{
      public static void main(String st[])
      {
            System.out.println(count("my name", 'm', 0));
      }

      public static int count(String str, char ch)
      {
            //return count(str, ch, 0);
            return nonRecursiveCount(str, ch);
      }
      public static int count(String name, char ch, int from)
      {
            int index = name.indexOf(ch, from);
            if (index < 0)
                  return 0;
            else
                  return 1 + count(name, ch, index + 1);
      }

      public static int nonRecursiveCount(String name, char ch)
      {
            int index = name.indexOf(ch, 0);
            int counter = 0;
            while (index < 0)
            {
                  counter++;
                  index = name.indexOf(ch, index);
            }

            return counter;
      }
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
civicy2kAuthor Commented:
aozarov,

does the int index keep track of how many times char1 appears in sentences? Because mine is like this now and doesn't seems very good:

public class Occur
{
      public static void main( String args[] )
      {
            int count = 0;
            Scanner scanner = new Scanner( System.in );
            System.out.println( "Enter a line of text:" );
            System.out.println();
            String sentence = scanner.nextLine();
            
            Scanner input = new Scanner( System.in );
            System.out.println( "\nEnter a search character:" );
            System.out.println();
            String char1 = input.nextLine();
            System.out.println();
                        
            int index = sentence.indexOf( char1 );
            if (index < 0)
               return 0;
          else
               return 1 + count(sentence, char1, index + 1);
             
           System.out.printf( "%d", index );
     
      }
}      
0
 
aozarovCommented:
JakobA -> System.out.println("mmm".split("m").length); // this will return 0
civicy2k -> you are not doing it in a loop
0
 
aozarovCommented:
civic2k -> sorry I don't think I read you well.
To get the count of char1 you need to do

int index = count(sentence, char1.trim().charAt(0), index + 1);
System.out.printf( "%d", index );
0
 
aozarovCommented:
Oops, wrong again.

int index = count(sentence, char1.trim().charAt(0),  0);
System.out.printf( "%d", index );
0
 
aozarovCommented:
The method gets the string then the character to look for  and 0 for (start from the begining)
char1.trim().charAt(0) gets a character from your char1 string
0
 
aozarovCommented:
You can try to call the other methods I send in my second post. (they all return the same result)
0
 
JakobACommented:
aozarow >> you are right. I did not know that funny rule about trailing empty strings. sorry.
0
 
civicy2kAuthor Commented:
aozarow,
I modified per your advise, can you please tell me what's wrong with mine?


public class Occur
{
      public static void main( String args[] )
      {
            int count = 0;
            Scanner scanner = new Scanner( System.in );
            System.out.println( "Enter a line of text:" );
            System.out.println();
            String sentence = scanner.nextLine();
            
            Scanner input = new Scanner( System.in );
            System.out.println( "\nEnter a search character:" );
            System.out.println();
            String char1 = input.nextLine();
            System.out.println();
            
            System.out.printf( "%s is located at index %d\n", char1, sentence .indexOf( char1 ) );
      }
     public static int count(String name, char ch, int from)
     {
          int index = name.indexOf(ch, from);
          if (index < 0)
               return 0;
          else
               return 1 + count(name, ch, index + 1);
     }
     
            int index = count(sentence, char1.trim().charAt(0),  0);
            System.out.printf( "%d", index );
      
}      
0
 
aozarovCommented:
This:

int index = count(sentence, char1.trim().charAt(0),  0);
System.out.printf( "%d", index );

should be inside the main method
0
 
civicy2kAuthor Commented:
thats what I thought, but then it said
public static int count(String name, char ch, int from)
is illegal start of expression
0
 
aozarovCommented:
leave this outside:
public static int count(String name, char ch, int from)
     {
          int index = name.indexOf(ch, from);
          if (index < 0)
               return 0;
          else
               return 1 + count(name, ch, index + 1);
     }

Just put those two lines:
nt index = count(sentence, char1.trim().charAt(0),  0);
          System.out.printf( "%d", index );
inside the main method  before
System.out.printf( "%s is located at index %d\n", char1, sentence .indexOf( char1 ) );
0
 
civicy2kAuthor Commented:
aozarov,

thank you so much, you are very helpful!

take care.
0
 
aozarovCommented:
:-)
0
 
aozarovCommented:
Venabili,
I didn't assume that 4 lines of code is a home work questions (the rest of the code I provided does the same but using different
aproaches). One need just to google http://www.google.com/search?hl=en&q=java+count+the+occurrences+of+a+character+in+a+string
to get hundreds of complete answers for this question. As I told you before I don't care about the points and I am only trying to help.

>> I am really tired of this.
Fine, I don't want to cause any more burden. I want to remove all my points and cancel my account. I could not find how to do that.
Can you please do that for me or advice me of how I can do it myself.
After that I expect to no longer get any emails from E.E
Thanks and sorry for the trouble,
Arie.
0
 
VenabiliCommented:
aozarov ,

Wait a second, please.
Yes - they need to go to google and that is what they are supposed to do.. instead of not even making a research and directly asking here :) That's the idea.

You are not causing any burden :) I am tired from all experts that are doing this all the time :( That's all... Check your mail please

Hopefully you will decide to stay :)

Friendly,
Venabili
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 11
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now