Searching for specific character in string with st

2019-09-04 16:54发布

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);
}
}

7条回答
Emotional °昔
2楼-- · 2019-09-04 17:39

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.

查看更多
The star\"
3楼-- · 2019-09-04 17:44

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;
}
查看更多
相关推荐>>
4楼-- · 2019-09-04 17:45

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++;
查看更多
Anthone
5楼-- · 2019-09-04 17:46
private static boolean hasAnyB(String str) {
  return str.toLowerCase().contains("b");
}
查看更多
\"骚年 ilove
6楼-- · 2019-09-04 17:49

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");

}
查看更多
做个烂人
7楼-- · 2019-09-04 17:55

Something like this:

static boolean check(String str){
    if(str.indexOf('B')>0 || str.indexOf('b')>0 )
        return true;
    else
        return false;
}
查看更多
登录 后发表回答