Java >> Tutoriel Java >  >> Tag >> String

Programme Java pour compter les occurrences de sous-chaîne

Obtenez une chaîne et une sous-chaîne et comptez l'occurrence de la sous-chaîne dans la chaîne.

Exemple d'entrée 1 :

divertissement

fr

Exemple de sortie 1 :

2

Programme ou solution

				
			
					
//Count the occurences of given substring in a String...

import java.util.*;

class Program
{
  public static void main(String args[])
  {
      int i,k,count=0;
      String full,half;
      Scanner sc=new Scanner(System.in);

      System.out.println("Enter The String:");
      full=sc.next();

      System.out.println("Enter The Sub-String:");
      half=sc.next();

       int len1=full.length();
       int len2=half.length();

       for(i=0;i<len1;i++)
          {
                   int j=0,b=0;

                   if(full.charAt(i)==half.charAt(j))
                      {

                                for(k=i;j<len2;k++,j++)
                                    {

                                             if(full.charAt(k)!=half.charAt(j))
                                                 {
                                                             b=1;
                                                             break;
                                                  }

                                      }
                                  if(b==0)
                                  {
                                           count++;
                                  }

                      }

             }

            System.out.println("The Count Is:"+count);


     }
}
			
				
			

Explication du programme


Balise Java