Searching for specific character in string with st

2019-09-04 17:26发布

问题:

I have to make a program that counts the number of the letter B in a string. I got that part already, but it also requires me to use a static method that returns true or false based on if the string has any Bs in it and i really don't see how to fit that part in.

import java.util.Scanner;
public class CountB {

// write the static method “isThisB” here
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a string: ");
String w = keyboard.nextLine();
int count=0;
for (int i=0; i<w.length(); i++)
{
    if (w.charAt(i)=='B'||w.charAt(i)=='b')
    {
        count++;
    }
}
System.out.println("Number of B and b: "+ count);
}
}

回答1:

Something like this:

static boolean check(String str){
    if(str.indexOf('B')>0 || str.indexOf('b')>0 )
        return true;
    else
        return false;
}


回答2:

private static boolean hasAnyB(String str) {
   return str.contains("B") || str.contains("b");
}


回答3:

Use the built-in matches() method, which uses regex:

private static boolean hasB(String str) {
    return str.matches(".*[bB].*");
}

Using regex is a near way to handle mixed case issues.



回答4:

Just Deploy all coding inside a static method that's it

public static void main(String[] args) 
{
  methodOne("Pass string over here");
}

public static boolean methodOne(String s)
{
   return s.contains("B");

}


回答5:

To get the count of b or B you can do

int bCount = w.replaceAll("[^Bb]", "").length();

If you have to use a hasB method you could do it like this, though its pretty inefficient and longer than it needs to be

int count = 0;
for(String ch: w.split("")) // one character at a time.
    if(hasB(ch))
       count++;


回答6:

private static boolean hasAnyB(String str) {
  return str.toLowerCase().contains("b");
}


回答7:

The easiest i could think.

static boolean isThisB(String s, int count) {
    for(int i=0; i<s.lenght(); i++) {
        char c = s.charAt(i);
        if(c == 'b' || c == 'B')
            count ++;
    }

    return count > 0;
}