I need to make a program in which the user types a string and substring, and tells how many times this substring occurs in the main string. Ex: Main chain: "banana" Substring: "na" Repetitions: 2.
I've already thought about using a String vector, or the Substring command but I have not gotten anything so far.
The only attempt I could at least mount the code was:
Scanner s = new Scanner (System.in);
int controle, contador;
contador = 0;
String cadeia, palavra, substring;
substring="";
System.out.println("Insira uma frase e/ou palavras: ");
cadeia = s.nextLine();
System.out.println("Selecione uma palavra a ser verificada na cadeia: ");
palavra = s.nextLine();
char inicioSubstring = palavra.charAt(0);
int fnalSubstring = (palavra.length()-1);
char finalSubstring = palavra.charAt(fnalSubstring);
int inicioSubs = -1;
int fimSubs = -1;
for (controle = 0; controle < cadeia.length(); controle++)
{
if (cadeia.charAt(controle) == inicioSubstring)
{
inicioSubs = controle;
}
if (cadeia.charAt(controle) == finalSubstring)
{
fimSubs = controle;
}
if(inicioSubs != -1 && fimSubs != -1)
{
substring = cadeia.substring(inicioSubs, fimSubs);
if(substring.equalsIgnoreCase(palavra))
{
contador++;
}
}
}
System.out.println(contador);