-2

I've just started to learn how to write code using Java and am trying to make a boolean function that takes a string and returns true is a character 's' in a string is always followed(somewhere) by the character 't', and false otherwise. So for example, "stay" should return true; "tta" should return false; "cc" should return true because 's' does not appear at all therefore any 's' IS preceded by an 't', there just are no 't's.How would I go about this?

1 Answers1

0

The easiest approach would be something like this

private static boolean findSfollowedByT(String string) {
    if (!string.contains("t") && !string.contains("s"))
        return true;
    if (string.contains("s") && string.indexOf("s") < string.lastIndexOf("t"))
        return true;
    else
        return false;
}

or a more compact version

private static boolean findSfollowedByT(String string) {
    return !string.contains("t") && !string.contains("s") || string.contains("s") && string.indexOf("s") < string.lastIndexOf("t");
}

results with test strings

"stay" returns: true
"cc" returns: true
"tta" returns: false
"string" returns: true
"tst" returns: true
scsere
  • 599
  • 2
  • 14
  • 21