Finding repeated words on a string and counting the repetitions

后端 未结 29 889
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  逝去的感伤
    2021-02-05 18:29

    //program to find number of repeating characters in a string
    //Developed by Subash
    
    
    import java.util.Scanner;
    
    public class NoOfRepeatedChar
    
    {
    
       public static void main(String []args)
    
       {
    
    //input through key board
    
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter a string :");
    
    String s1= sc.nextLine();
    
    
        //formatting String to char array
    
        String s2=s1.replace(" ","");
        char [] ch=s2.toCharArray();
    
        int counter=0;
    
        //for-loop tocompare first character with the whole character array
    
        for(int i=0;i1)
            {
                boolean flag=false;
    
                //for-loop to check whether the character is already refferenced or not 
                for (int k=i-1;k>=0 ;k-- )
                {
                    if(ch[i] == ch[k] ) //if the character is already refferenced
                        flag=true;
                }
                if( !flag ) //if(flag==false) 
                    counter=counter+1;
            }
        }
        if(counter > 0) //if there is/are any repeating characters
                System.out.println("Number of repeating charcters in the given string is/are " +counter);
        else
                System.out.println("Sorry there is/are no repeating charcters in the given string");
        }
    }
    

提交回复
热议问题