DEV Community

Guna Sekaran
Guna Sekaran

Posted on

Counting Character Appearances in a String

package array;

public class Character_count {

        public static void main(String[] args) {

            String s="Gunasekaran";     
            char[]c=s.toCharArray();

                for(int j=0;j<c.length;j++) {

                    char key=c[j];
                    int count=1;

                    if (key == '*') {
                        continue;
                    }


                for(int i=j+1; i<c.length; i++) {

                    if(key==c[i]) {

                        c[i]='*';
                        count++;
                    }

                }   


                System.out.println(key+"appears"+ count);


                }


        }
}

.........................................................................

OUTPUT:

G Appears 1 Times
u Appears 1 Times
n Appears 2 Times
a Appears 3 Times
s Appears 1 Times
e Appears 1 Times
k Appears 1 Times
r Appears 1 Times

Enter fullscreen mode Exit fullscreen mode
                 FINDING THE CHARACTER WHICH HAS THE ONE COUNT VALUE

package array;

public class Character_count {

        public static void main(String[] args) {

            String s="Gunasekaran";     
            char[]c=s.toCharArray();

                for(int j=0;j<c.length;j++) {

                    char key=c[j];
                    int count=1;

                    if (key == '*') {
                        continue;
                    }


                for(int i=j+1; i<c.length; i++) {

                    if(key==c[i]) {

                        c[i]='*';
                        count++;
                    }

                }   

                if (count == 1) { // using this condition for printing character has one count value 

                System.out.println(key+ " Appears "+ count+ " Times");
                }

                }


        }
}

.........................................................................

OUTPUT:

G Appears 1 Times
u Appears 1 Times
s Appears 1 Times
e Appears 1 Times
k Appears 1 Times
r Appears 1 Times

Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay