2

I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.

I want to make the following changes:

1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.

2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.

3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.

Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.

So this is my code so far:

public class Count { 
    static final int MAX_CHAR = 256; //is this part even needed?

    public static void countString(String str) 
    { 
        // Create an array of size 256 i.e. ASCII_SIZE 
        int count[] = new int[MAX_CHAR]; 

        int length = str.length(); 

        // Initialize count array index 
        for (int i = 0; i < length; i++) 
            count[str.charAt(i)]++; 

        // Create an array of given String size 
        char ch[] = new char[str.length()]; 
        for (int i = 0; i < length; i++) { 
            ch[i] = str.charAt(i); 
            int find = 0; 
            for (int j = 0; j <= i; j++) { 

                // If any matches found 
                if (str.charAt(i) == ch[j])  
                    find++;                 
            } 

            if (find == 1)  
                System.out.println("Number of Occurrence of " + 
                 str.charAt(i) + " is:" + count[str.charAt(i)]);             
        } 
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str); 
    } 
} 
user10369729
  • 67
  • 2
  • 3
  • 9
  • Need some clarifications. Do you want a method that will count the occurrence of any given character and print the occurrences and the count? – Shafin Mahmud Sep 16 '18 at 04:34

8 Answers8

2

You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.

public class Count {
static final int MAX_CHAR = 256; 

    private static void countString(String str, Character character) {
        int [] counts = new int[MAX_CHAR];
        char [] chars = str.toCharArray();
        for (char ch : chars) {
            if (character!=null && character!=ch) {
                continue;
            }
            counts[ch]++;
        }
        for (int i=0; i<counts.length; i++) {
            if (counts[i]>0) {
                System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
            }
        }
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        countString(str, 'e');
    }
}
tom
  • 1,331
  • 1
  • 15
  • 28
  • Thank you tom. So I guess I just want a simple program to print all the a in a string, and then count the appearance of them. Then I want to mess around the final code on my own so I can learn more on Java. Also do you want to change anything in my code or see anything could be improved? – user10369729 Sep 16 '18 at 04:38
  • Tom can you write the full code here? I'm just a beginner. I will accept your answer – user10369729 Sep 16 '18 at 04:44
  • You probably should "break" after the `find++` or else you will not handle the case where more than one of the same character appears in the string. Also I wouldn't iterate using `for (int i=0...)` I would just use `for (Character c : str.toCharArray())`. Just a couple of things different here. – tom Sep 16 '18 at 04:44
  • OK I edited my answer to put the full class. – tom Sep 16 '18 at 04:50
2

Try this

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str = input.nextLine();

    // Whatever is the input it take the first character.
    char searchKey = input.nextLine().charAt(0);
    countString(str, searchKey);
}

public static void countString(String str, char searchKey) {
    // The count show both number and size of occurrence of searchKey
    String count = ""; 
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == searchKey)
            count += str.charAt(i) + "\n";
    }
    System.out.println(count + "\nNumber of Occurrence of "
                    + searchKey + " is " + count.length() + " in string " + str);
}
1
  1. you can take input from user "which character he/she wants to count".
    1. To show the occurrence of character see code below.
    2. You need to import java.util.Scanner class.

Here is your code:

import java.util.Arrays;
import java.util.Scanner;

public class Count { 

    public static void countString(String str) 
    { 

        if(str!=null) {
            int length = str.length(); 

            // Create an array of given String size 
            char ch[] = str.toCharArray();
            Arrays.sort(ch);
            if(length>0) {
                char x = ch[0];
                int count = 1;
                for(int i=1;i<length; i++) {
                    if(ch[i] == x) {
                        count++;
                    } else {
                        System.out.println("Number of Occurrence of '" + 
                                 ch[i-1] + "' is: " + count);
                        x= ch[i];
                        count = 1;
                    }
                }
                System.out.println("Number of Occurrence of '" + 
                     ch[length-1] + "' is: " + count);
            }
        }
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str =  input.nextLine();//"geeksforgeeks"; 
        countString(str); 
    } 
} 
Aagam Jain
  • 1,546
  • 1
  • 10
  • 18
1

See the snippet below for a way to do it in Java8

public static void main(String[] args) {
    // printing all frequencies
    getCharacterFrequency("test")
            .forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));

    // printing frequency for a specific character
    Map<Character, Long> frequencies = getCharacterFrequency("test");
    Character character = 't';
    System.out.println("Frequency for t: " +
            (frequencies.containsKey(character) ? frequencies.get(character): 0));
}

public static final Map<Character, Long> getCharacterFrequency(String string){
    if(string == null){
        throw new RuntimeException("Null string");
    }
    return string
             .chars()
             .mapToObj(c -> (char) c)
             .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

}
1

You just have to modify this line of code:

using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.

    if (find == 1) { 
       for(int k=0;k< count[str.charAt(i)];k++)
          System.out.print(str.charAt(i)+",");
       System.out.println(count[str.charAt(i)]); 
    }

Edit: modified based on your comment, if you want the whole code

  import java.util.*;

public class Count { 
static final int MAX_CHAR = 256; //is this part even needed?

public static void countString(String str) 
{ 
    // Create an array of size 256 i.e. ASCII_SIZE 
    int count[] = new int[MAX_CHAR]; 

    int length = str.length(); 

    // Initialize count array index 
    for (int i = 0; i < length; i++) 
        count[str.charAt(i)]++; 

    // Create an array of given String size 
    char ch[] = new char[str.length()]; 
    for (int i = 0; i < length; i++) { 
        ch[i] = str.charAt(i); 
        int find = 0; 
        for (int j = 0; j <= i; j++) { 

            // If any matches found 
            if (str.charAt(i) == ch[j]){  
                 //System.out.println(str.charAt(i));
                find++;  
            }                   
        } 

    if (find == 1) { 
       for(int k=0;k< count[str.charAt(i)];k++)
          System.out.print(str.charAt(i)+",");
       System.out.println(count[str.charAt(i)]); 
    }

    } 
} 
public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    String str = "geeksfeorgeeks"; 
    str = input.nextLine();
    countString(str); 
} 
} 

output

g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
1

I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this

public class Count {
 static final int MAX_CHAR = 256;
 public static void main(String[] args)    {
     Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str, 'e'); 
 }
 public static void countString(String str, char value) 
 { 
     List<String> l = Arrays.asList(str.split(""));
     // prints count of each character occurence in string
     l.stream().forEach(character->System.out.println("Number of Occurrence of " + 
             character + " is:" + Collections.frequency(l, character)));
     if(!(Character.toString(value).isEmpty())) {
         // prints count of specified character in string
         System.out.println("Number of Occurrence of " + 
                 value + " is:" + Collections.frequency(l, Character.toString(value)));
     }

 } 

And this is the code with requirements mentioned in comments

public class Count {
static final int MAX_CHAR = 256;
 public static void main(String[] args)    {
     Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str, 'e'); 
 }
 public static void countString(String str, char value) 
 { 
     String[] arr = str.split("");
     StringBuffer tempString = new StringBuffer();
     for(String s:arr) {
         tempString.append(s);
         for(char ch:s.toCharArray()) {
             System.out.println("Number of Occurrence of " + 
                     ch + " is:" + tempString.chars().filter(i->i==ch).count());
         }
     }
     if(!(Character.toString(value).isEmpty())) {
         StringBuffer tempString2 = new StringBuffer();
         for(String s:arr) {
             tempString2.append(s);
             for(char ch:s.toCharArray()) {
                 if(ch==value) {
                 System.out.println("Number of Occurrence of " + 
                         ch + " is:" + tempString2.chars().filter(i->i==ch).count());
                 }
             }
         } 
     }

   } 
} 
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

You can use this code below;

import java.util.Scanner;

public class Count {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();

        char key = input.nextLine().charAt(0);
        countString(str, key);
    }

    public static void countString(String str, char searchKey) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == searchKey)
                count++;
        }
        System.out.println("Number of Occurrence of "
                + searchKey + " is " + count + " in string " + str);

        for (int i = 0; i < count; i++) {
            System.out.println(searchKey);
        }

        if (count > 0) {
            System.out.println(count);
        }
    }
}
drowny
  • 2,067
  • 11
  • 19
0

I would create a method such as the one below:

public static String stringCounter(String k) {
    char[] strings = k.toCharArray();
    int numStrings = strings.length;
    Map<String, Integer> m = new HashMap<String, Integer>();
    int counter = 0;
    for(int x = 0; x < numStrings; x++) {
        for(int y = 0; y < numStrings; y++) {
            if(strings[x] == strings[y]) {
                counter++;
            }

        }m.put(String.valueOf(strings[x]), counter);

        counter = 0;
    }
    for(int x = 0; x < strings.length; x++) {
        System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
    }
    return m.toString();
  }



}

Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:

I tested the method in the main method by entering the String "Hello world":

System.out.println(stringCounter("Hello World"));

And here is our final output:

1H
1e
3l
3l
2o
1 
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}

You get the number of times each character occurs in the String and you can use either the Map or print the output.

Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:

Scanner scan = new Scanner(System.in);
System.out.println("Please enter  a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));

You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:

Please enter  a String: 
Hello World
1H
1e
3l
3l
2o
1 
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27