damtypo
damtypo

Reputation: 160

Find if there are two specfic characters in a string

I'm doing some java exercises and I can't figure why the answer isn't this one.

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

The question asks to return true if a given string(str) has "bob" in it, except the middle character does not need to be "o". The above code returns true for strings three characters in length which meet the condition, like "bob" or "bbb", but false for strings longer than that i.e "bobdfgkabcb". I've literally spent all day trying to solve this and another similar problem so I'd be gratefull to be told why its wrong.

Thanks.

Upvotes: 0

Views: 1287

Answers (5)

Akhil
Akhil

Reputation: 9

public boolean bobThere(String str) {
    if(str.length()<3)
        return false;
    else {
        for(int i=0;i<str.length()-2;i++){
            if(str.charAt(i)=='b'&&str.charAt(i+2)=='b') return true;
        }
    }
    return false;
}

Upvotes: 0

Gestalt
Gestalt

Reputation: 187

Here's an implementation which uses indexOf() method of String instead.

public boolean bobThere(String str) {
      int c=str.indexOf('b');
      int l=str.length();
      for(;c<l-2 && c!=-1;c=str.indexOf('b',c))
      {
      if(str.charAt(c+2)=='b') 
      return true;
      c++;
      }
      return false;
    }

Upvotes: 0

Emmanuel Okafor
Emmanuel Okafor

Reputation: 13

Got a string error so this was my solution:

public boolean bobThere(String str) {
boolean returner = false;
if(str.contains("bob")){
  return true;
}
for(int i = 0; i < str.length() - 2; i++){
  if(str.charAt(i) == 'b'){
      if(str.charAt(i + 2) == 'b')
       returner = true;
 
  }
}
if(returner == true){
  return returner;
}
return false;
}

If you get the error, minus the length by the location of the second variable.

Upvotes: 0

M.zar
M.zar

Reputation: 9

you can use to it:

public boolean bobThere(String str) {
  for (int i = 0 ; i < str.length()-2 ; i++){
  if( str.substring(i , i+1).equals("b") && str.substring(i+2 , i+3).equals("b"))
  return true;}

  return false;
  }

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Change your code to :

for (int i=0;i<str.length()-2;i++)  {
    if ((str.charAt(i)=='b') && (str.charAt(i+2)=='b')) {// check 1st and 3rd character, 2nd and 4th character etc
    return true; }
    }
 return false;

Or you could try regex like this : str.matches(".*b[a-zA-Z]b.*")

Upvotes: 3

Related Questions