fork download
  1. import java.lang.reflect.Field;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. test("foo", "foo", true);
  7. test("foo", "foobar", true);
  8. test("oob", "foobar", true);
  9. test("oobar", "foobar", true);
  10. test("barbar", "foobar", false);
  11. test("blip", "foo", false);
  12. test("", "troll", true);
  13. test("foo", "", false);
  14. test("test", "testing", true);
  15. test("dog", "cat", false);
  16. test("test", "Testing", false);
  17. }
  18.  
  19. private static void test(String needle, String haystack, boolean expected) {
  20. boolean isSubstring = isSubstring(needle, haystack);
  21. if (isSubstring != expected) {
  22. System.out.println("You're fired!");
  23. }
  24. System.out.printf("\"%s\" contained in \"%s\"? %b expected: %b%n", needle, haystack, isSubstring, expected);
  25. }
  26.  
  27. public static boolean isSubstring(String needle, String haystack) {
  28.  
  29. if (haystack.length() < needle.length()) {
  30. return false;
  31. }
  32.  
  33. char[] needleChars = getCharArray(needle);
  34. char[] haystackChars = getCharArray(haystack);
  35. for (int i = 0; i < haystack.length(); i++) {
  36. if (isSubstringAtPosition(needleChars, haystackChars, i)) {
  37. return true;
  38. }
  39. }
  40. return false;
  41.  
  42. }
  43.  
  44. private static boolean isSubstringAtPosition(char[] needle, char[] haystack, int haystackPosition) {
  45. if (needle.length > (haystack.length - haystackPosition)) {
  46. return false;
  47. }
  48. for (char c : needle) {
  49. if (haystack[haystackPosition++] != c) {
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55.  
  56. public static char[] getCharArray(String string) {
  57. Field value;
  58. try {
  59. value = String.class.getDeclaredField("value");
  60. value.setAccessible(true);
  61. return (char[]) value.get(string);
  62. } catch (SecurityException e) {
  63. e.printStackTrace();
  64. } catch (NoSuchFieldException e) {
  65. e.printStackTrace();
  66. e.printStackTrace();
  67. } catch (IllegalAccessException e) {
  68. e.printStackTrace();
  69. }
  70. throw new RuntimeException("oops");
  71. }
  72. }
  73.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
"foo" contained in "foo"? true expected: true
"foo" contained in "foobar"? true expected: true
"oob" contained in "foobar"? true expected: true
"oobar" contained in "foobar"? true expected: true
"barbar" contained in "foobar"? false expected: false
"blip" contained in "foo"? false expected: false
"" contained in "troll"? true expected: true
"foo" contained in ""? false expected: false
"test" contained in "testing"? true expected: true
"dog" contained in "cat"? false expected: false
"test" contained in "Testing"? false expected: false