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?
Asked
Active
Viewed 798 times
-2
-
boolean st(String s) { boolean seenS = true; while(true) { if (s.equals("") return seenS;) char c1='s'; char c2='t' } } – m.lewis1995 Feb 07 '16 at 22:24
-
`s.matches(".*s.*t.*") || !s.contains("t")` – Feb 07 '16 at 22:32
-
I'm trying To use if statements and while statements if that's possible? – m.lewis1995 Feb 07 '16 at 22:44
1 Answers
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
- 621
- 2
- 15
- 25