How do I check if a string contains the second string in its character order?
I've just started and I'm completely lost in how to do this
I want to be able to check whether the string has a smaller string, and return true if the string contains the letters of the string in order
I'm not sure how to ensure the alphabetical order of the second string, even if there are other letters between them
An example is "Chemistry" which returns true for the string "hit"
But for the string "him", it returns false
Any help would be appreciated
Editor: Thank you. I changed "substring" to string As I said, I just started and didn't know what it meant I really appreciate all the help It should move me in the right direction
Solution
The general method is to iterate over the characters of the longer string ("Chemistry"), always tracking the index of the next required character in the shorter string ("hit" – first 0, then 1 once h is found, once you find me, and then when you find that you have finished) For example:
public static boolean containsSubsequence( final String sequence,final String subsequence) { if (subsequence.isEmpty()) { return true; } int subsequenceIndex = 0; for (int i = 0; i < sequence.length(); ++i) { if (sequence.charAt(i) == subsequence.charAt(subsequenceIndex)) { ++subsequenceIndex; if (subsequenceIndex == subsequence.length()) { return true; } } } return false; }