Java > Warmup-2 > countXX (CodingBat Solution)

Problem:

Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

countXX("abcxx") → 1
countXX("xxx") → 2
countXX("xxxx") → 3


Solution:

int countXX(String str) {
  int count = 0;
  for (int i = 0; i < str.length()-1; i++) {
    if (str.substring(i, i+2).equals("xx")) count++;
  }
  return count;
}

// Solution notes: the loop is shortened to end at str.length()-1
// so we can pull out a length 2 substring without going out of bounds.
// Remember to use equals() to compare strings, not ==.


3 comments :

  1. public int countXX(String str)
    {
    int count=0;
    char[] arr=str.toCharArray();
    for(int i=0;i<arr.length-1;i++)
    {
    if(arr[i]=='x'&&arr[i+1]=='x')
    count++;
    }
    return count;
    }

    ReplyDelete
  2. private final int countXX(String word) {
    if(word.length() <= 2 && !word.equals("xx")){
    return 0;
    }
    if(word.charAt(0) == 'x' && word.charAt(1) == 'x'){
    return 1 + countXX(word.substring(1));
    }
    return countXX(word.substring(1));
    }

    ReplyDelete
  3. int countXX(String str) {

    int count = 0;

    for(int i = 0; i < str.length()-1; i++){

    if(str.charAt(i) == 'x' && str.charAt(i+1) == 'x'){
    count++;
    }
    }

    return count;

    }

    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