public class MyWord {
final static String[] MY_WORD = { "It's could only be Heineken","Hello,I have to go to somewhere","Someday, I will find my way","Life is not beautiful" };
public static void main(String args[]){
int count,pos;
String[] str = MyWord.MY_WORD;
for(int i=0;i<str.length;i++) {
count = 0;
System.out.println("Find 'e' in this sentence "+str[i]);
System.out.print("Found 'e' at index :");
for(int j=0;j<str[i].length();j++) {
if (str[i].charAt(j)=='e') {
count++;
System.out.print(" "+j);
}
}
System.out.println("\nTotal 'e' : "+count);
System.out.println("**********************************");
}
}
}
แต่ทีนี้มีโจทย์เพิ่มคือให้หาคำว่า The ในประโยค ซึ่งผมหมดปัญญาจิงๆ รบกวนหลายๆท่านในที่นี้ช่วยทีครับ
public class MyWord {
final static String[] MY_WORD = {
"It's could The only be Heineken The",
"Hello,I The have to go to somewhere The",
"The Someday, The I will The find my way",
"Life is not The beautiful"
};
public static void main (String args[]) {
int count;
String[] str = MyWord.MY_WORD;
String strNeed = "The";
for(int i=0;i<str.length;i++) {
count = 0;
System.out.println("Find 'The' in this sentence "+str[i]);
System.out.print("Found 'The' at index :");
for(int j=0;j<str[i].length();j++) {
if (j <= str[i].length()-3) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(str[i].charAt(j));
strBuilder.append(str[i].charAt(j+1));
strBuilder.append(str[i].charAt(j+2));
String strText = strBuilder.toString();
if (strText.equals(strNeed)) {
count++;
System.out.print(" "+j);
}
}
}
System.out.println("\nTotal 'The' : "+count);
System.out.println("**********************************");
}
}
}