Java > Warmup-2 > doubleX (CodingBat Solution)

Problem:

Given a string, return true if the first instance of "x" in the string is immediately followed by another "x".

doubleX("axxbb") → true
doubleX("axaxax") → false
doubleX("xxxxx") → true


Solution:

boolean doubleX(String str) {
  int i = str.indexOf("x");
  if (i == -1) return false; // no "x" at all

  // Is char at i+1 also an "x"?
  if (i+1 >= str.length()) return false; // check i+1 in bounds?
  return str.substring(i+1, i+2).equals("x");
  
  // Another approach -- .startsWith() simplifies the logic
  // String x = str.substring(i);
  // return x.startsWith("xx");
}


7 comments :

  1. boolean doubleX(String str) {

    for(int i=0;i<str.length()-1;i++){
    if(str.charAt(i)=='x'){
    if (str.charAt(i+1)=='x') {
    return true;
    } else {
    return false;
    }
    }
    }
    return false;
    }

    ReplyDelete
  2. private final boolean doubleX(String word) {
    return (word.indexOf("x") >= 0) && word.substring(word.indexOf("x")).startsWith("xx");
    }

    ReplyDelete
  3. private final boolean doubleX(String word) {
    if(word.indexOf("x") < 0) {
    return false;
    }
    return word.substring(word.indexOf("x")).startsWith("xx");
    }

    ReplyDelete
  4. boolean doubleX(String str) {
    return str.startsWith("xx")||str.startsWith("xx",1) ;
    }

    ReplyDelete
  5. Another way

    boolean doubleX(String str) {
    return !str.contains("x") ? false :
    str.substring(str.indexOf("x")).startsWith("xx");
    }

    ReplyDelete
  6. boolean doubleX(String str) {
    boolean ans=false;
    int index =str.indexOf("x"), len =str.length();

    if (index !=-1 && index<len-1 ){
    String s = str.substring(index);
    if (s.startsWith("xx")) {
    ans =true;
    }
    }
    return ans;
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact