-1

I'm currently doing this task. In the first part of the task it required me to check a string with boolean. For it to return true and only true only if every character of the input string is one of a, A, c, C, g, G, t or T. Return false if the string is null or empty. I'm a bit lost at this because i'm not sure how to compare it. I'm looking at using array and checking with the for loop for the string. Is it a feasible option? If not are there any other options i should look at?

This is my code so far. I put the string s to lower case to make the comparing easier with only 4 characters to do so.

    public static boolean isDNASequence(String s) {
    boolean isDNASequnce = false;
    char [] acceptableInput = {'a', 'c', 'g', 't'};
    String x = s.toLowerCase();

I'm a very big java noob so please excuse me if i don't know my way around here :D

4

4 回答 4

1

Try using using regular expressions.
The pattern [aAcCgGtT]+ should match what you're looking for.

e.g.:

public static boolean isDNASequence(s) {
  return s.matches("^[aAcCgGtT]+$");
}

To explain further, the pattern in the quotes says to match: ^ - from the start of the string [aAcCgGtT] - any of these characters + - at least once $ - to the end of the string

于 2013-04-28T04:13:04.960 回答
0

尝试这个

public static boolean isDNASequence(String s) {
    for (int i = 0; i < s.length(); i++) {
        if ("AaCcGgTt".indexOf(s.charAt(i)) == -1) {
            return false;
        }
    }
    return true;
}
于 2013-04-28T04:46:21.980 回答
0

我想这就是你要找的。

public static boolean isDNASequence(String s) {
    char[] acceptableInput = { 'a', 'c', 'g', 't' };
    String x = s.toLowerCase();

    for (int i = 0; i < x.length(); i++) {

        boolean isAcceptable = false;

        for (int j = 0; j < acceptableInput.length; j++) {
            if (x.charAt(i) == acceptableInput[j])
                isAcceptable = true;
        }

        if (isAcceptable == false)
            return false;

    }
    return true;

}
于 2013-04-28T04:36:46.380 回答
0

您可以在 Java 文档中找到方法String.matches() 。如果字符串匹配正则表达式,它将返回 true。

正则表达式模式[aAcCgGtT]+可能是您正在寻找的。

我发现是学习正则表达式的非常好的指南!

于 2013-04-28T04:37:47.287 回答