-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.java
More file actions
63 lines (52 loc) · 1.56 KB
/
Strings.java
File metadata and controls
63 lines (52 loc) · 1.56 KB
1
/* * The only String methods that you are allowed to use in this assignment * are String.charAt(int) and String.length(). */public class Strings { /* * Tests two given strings for equality without using isEqual methods * * Returns true if and only if the two given strings represents the * same sequence of characters, false otherwise. * */ public static boolean isEqual(String s1, String s2) { if(s1.length() != s2.length()){ return false; } for(int i = 0; i< s1.length();i++){ if (s1.charAt(i) != s2.charAt(i)){ return false; } } return true; } /* * Returns a new string that is a substring of a given String s. * The substring begins at the specified start index (index) and extends * to the number of characters defined by length. * * For example: substring("Computer Science", 4, 6) returns "uter S" */ public static String substring(String s, int index, int length) { String result = ""; for (int i = 0; i < length; i++) result += s.charAt(index + i); return result; } /* * Returns the index within a given String s of the first occurrence of * the specified substring sub. If no occurrence of sub exists within s, * then -1 is returned. * * Examples: * indexOf("abracadabra", "c") returns 4 * indexOf("abracadabra", "s") returns -1 */ public static int indexOf(String s, String sub) { for (int i = 0; i < s.length() - sub.length() + 1; i++) if (isEqual(substring(s, i, sub.length()), sub)) return i; return -1; }}