Search code examples
javaarrayssubstringcharacter-arrays

Finding two different sub strings and printing everything between them in JAVA


String theString="gtcaatgccaataaagt";
char[] charArray = theString.toCharArray();
int len=theString.length();
boolean start = false,end1 = false;
for(int i=0;i<len;i++){
    if(charArray[i]=='a' && charArray[i+1]=='t' && charArray[i+2]=='g'){
        start=true;
    }
    if(charArray[i]=='t' && charArray[i+1]=='a' && charArray[i+2]=='a'){
        end1=true;
    }
}
while(start==true && end1==true){
    for(int i=0;i<len;i++){
        System.out.println(charArray[i]);
    }
}

I want to print the characters between "atg" and "taa" from the string "theString"... But with above code I am getting java.lang.ArrayIndexOutOfBoundsException. Don't know how to deal with it...And I think the mistake is in the first for loop..... but i don't know how to read "atg" first and then read "taa"


Solution

  • Something like this will work for you :

    public static void main(String[] args) {
        String s = "abcdefghijk";
        int i1 = s.indexOf("cd")+2; // add index + length of substring (i.e, 2)
        int i2 = s.indexOf("ij");
        System.out.println(s.substring(i1,i2));
    
    }
    
    O/P :
    efgh