nick
nick

Reputation: 323

search an item in a array

i have the String str="abc"; and i want to search if there is the letter "b" in it.I convert it to char[] and i create a for loop.this is my code [code]

      String str="abc";
      char c[] = str.toCharArray();

      for(int k=1;k<c.length;k++){
          if(c[k]=='b')
                {  
                System.out.println("yes");
                }
          else {
            System.out.println("no");}
                }

why does it print 'no'??

Upvotes: 1

Views: 131

Answers (3)

Sabya
Sabya

Reputation: 1429

You can do it in simpler way.

    String str1 = "abc";
    if(str1.contains("b")){
        System.out.println("i am here");
    }else{
        System.out.println("none");
    }

String class provides this method to search for any string in it .

If you want to use your code only then you can just modify it a little bit by adding a "break" statement.

      String str="abc";
      char c[] = str.toCharArray();

      for(int k=0;k<c.length;k++){
          if(c[k]=='b')
                {  
                System.out.println("yes");
                break;
                }
          else {
            System.out.println("no");}
                }

        }

Upvotes: 0

Mike Kwan
Mike Kwan

Reputation: 24447

You could just do str.contains("b").

In terms of your code, your k should be initialised to 0. The following code prints:

no yes no

String str = "abc";
char c[] = str.toCharArray();

for (int k = 0; k < c.length; k++) {
    if (c[k] == 'b') {
        System.out.println("yes");
    } else {
        System.out.println("no");
    }
}

A more conventional way to do it might be this:

public boolean contains( String strToCheck, char strContent ) {
    // return strToCheck.contains(strContent);

    for( int i = 0; i < strToCheck.length(); i++ ) {
        if( strToCheck.charAt(i) == strContent ) {
            return true;
        }
    }

    return false;
}

This would stop checking as soon as it finds the character. But really it is better to use the built-in API.

Upvotes: 4

Jigar Joshi
Jigar Joshi

Reputation: 240860

if you find your search key you should just stop looking.

and it is not necessary that on first iteration you will find your key

  String str="abc";
  char charArr[] = str.toCharArray();
  boolean found = false;

  for(char char: charArr){
      if(char =='b')
            {  
             found = true;
             break;
            }

    }

    if(found){  */Say Found*/ }else{/*Say no*/}

or simply

   stringInstance.contains("b");

Upvotes: 1

Related Questions