Wednesday 6 January 2010

Java programming fun

This is an interesting problem solved using Java, but without using any fancy extra methods.

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));

}
}

No comments:

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 ...