Reputation: 9
I am begener with JAVA.
I have a STRING String text = "un essai de méthode";
//this text can be change by the user
And I have a key word String key = "de";
//this Key word can also be changed by the user
As we can see, the key word "de" is present twice in the text: "un essai de méthode" And i need to count the number of times the key word repeats in the text.
int j = 0;
int nbCharKey, nbCharText;
int count = 0;
int c;
String text = "un essai de méthode do"; /*here is my text */
String key = "de"; /*here is my key word */
text = text.replaceAll(" ",""); /*i ignored all the spaces*/
nbCharText = text.length(); /* length of my text to create a ARRAY */
Character[] tabTEXT = new Character[nbCharText]; /*creating ARRAY for text */
for (int a = 0; a < nbCharText; a++){
tabTEXT[a]=text.charAt(a); /*adding the text into ARRAY*/
}
nbCharKey = key.length(); /* length of my key word to create a ARRAY */
Character[] tabKEY = new Character[nbCharKey]; /*creating ARRAY for key word */
for (int b = 0; b < nbCharKey; b++){
tabKEY[b] = key.charAt(b); /*adding my key word into ARRAY*/
}
int verif = 0; /*helps to count nb times the 1st char of key word repeats*/
char fKey = tabKEY[0];
for (int d = 0; d < nbCharText; d++){
if (fKey==tabTEXT[d]){
verif++; /*the 1st key letter "d" is found twice*/
}
//I DO NOT KNOW HOW TO CONTINUE THE REST
//I DO NOT KNOW HOW TO CONTINUE THE REST
//I DO NOT KNOW HOW TO CONTINUE THE REST
//I DO NOT KNOW HOW TO CONTINUE THE REST
if (fKey==tabTEXT[d]){
Character[] word = new Character[nbCharKey];
for(int e = 0; e<nbCharKey; e++){
word[e]=tabTEXT[d];
//System.out.println(nbCharKey);
System.out.println(word[e]);
d++;
}
}
Please help me.
Thanks in advance.
Upvotes: 1
Views: 80
Reputation: 112
String text = "un essai de méthode";
char[] charArrayText = text.toCharArray();
String key = "de";
char[] charArrayKey = key.toCharArray();
int count = 0;
boolean check = true;
for (int i = 0; i < charArrayText.length; i++) {
for (int j = 0; j < charArrayKey.length; j++) {
if (charArrayText[i + j] != charArrayKey[j] || i == charArrayText.length - 1) {
check = false;
break;
}
}
if (check) {
count++;
}
check = true;
}
System.out.println(count);
Upvotes: 2