Searching for specific character in string with static method

笑着哭i 提交于 2020-01-16 12:23:52

问题


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


来源:https://stackoverflow.com/questions/19855327/searching-for-specific-character-in-string-with-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!