public class TestIsSubString {
/*
* Write a isSubString method that searches for a specific string within
* another string; the method must return true if the former exists in the
* latter string. Otherwise, the method return false.
*/
public static boolean isSubString(String part, String whole) {
// The hard way, with nested loops instead of whole.indexOf(part)!= -1
// Note to self: local variables MUST be init'd
int hits = 0; // flag type of variable
boolean isFound = false;
for (int i = 0; i <= whole.length()-part.length(); i++) {
hits = 0;
//isFound = false;
for (int j = 0; j < part.length(); j++) {
if( part.charAt(j) == whole.charAt(i + j) ) {
hits ++;
}
}
System.out.println("Hits = " + hits + " | len = " + part.length());
if( hits == part.length() ) {
isFound = true;
}
}
return isFound;
}
public static void main(String[] args) {
String text = "The cat in the hat.";
System.out.println("isSubString(\"cat\", \"The cat in the hat.\") "
+ isSubString("cat", text));
System.out.println("isSubString(\"bat\", \"The cat in the hat.\") "
+ isSubString("bat", text));
System.out.println("isSubString(\"The\", \"The cat in the hat.\") "
+ isSubString("The", text));
System.out.println("isSubString(\"hat.\", \"The cat in the hat.\") "
+ isSubString("hat.", text));
}
}
Mostly Computer Science-related topics and resources, especially Linux and education (IB, IGCSE).
Wednesday, 6 January 2010
Java programming fun
This is an interesting problem solved using Java, but without using any fancy extra methods.
Subscribe to:
Post Comments (Atom)
Optimise Windows 10/11
How to optimise your Windows setup Just in case you need it. If you want a safe and conservative approach, just disable the background apps ...
-
Lenovo Ideapad S10-3 If you have a Lenovo Ideapad S10-3 (depicted above), and you want to test or install shiny new Ubuntu 10.10 on it,...
-
This brief post shows how to create a bi-dimentional array and describe it using IB pseudocode. It isn't stated in the IB Pseudocode in ...
-
In order to program in Java, you may want to follow the instructions and videos that I have prepared. They are simle and straightforward, an...
No comments:
Post a Comment