查找/打印以特定字母开头的特定单词

时间:2016-11-29 08:31:54

标签: java string methods static static-methods

这是主要的:

public class MiscStringOperationsDriver
{
    public static void main(String[] args)
    {
            // Test the wordCount method
            int numWords = MiscStringOperations.wordCount("There are five words here.");
            System.out.printf("Number of words: %d\n\n", numWords);

            // Test the arrayToString method
            char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
            String lettersToString = MiscStringOperations.arrayToString(letters);
            System.out.printf("The string is: %s\n\n", lettersToString);

            // Test the mostFrequent method
            char mostFrequentChar = MiscStringOperations.mostFrequent("aababbcddaa");
            System.out.printf("The most-frequent character is: %c\n\n", mostFrequentChar);

            // Test the beginWithB method
            String wordList = MiscStringOperations.beginWithB(
                            "Batman enjoyed some blueberries and a bacon burger in the Batmobile.");
            System.out.printf("The list of words is: %s\n\n", wordList);
    }
}

所有方法都在另一个类中。我正在努力使用last方法,即beginWithB方法。我还有其他一切工作。以下是我到目前为止这种方法的内容:

 public static String beginWithB(String wordlist) {
    String myStr = wordlist;
    for(String b: myStr.split(" ")){
        if(b.startsWith("b")||b.startsWith("B")){
            System.out.print(b);
        }   
    }

我正在努力找到一种方法,将以“b”或“B”开头的单词返回主页。有任何想法吗? (是的,我必须这样做)。

1 个答案:

答案 0 :(得分:1)

你的方法看起来很好,你只需要在返回String时创建一个字符串。 (见下面的代码)

<强> CODE

public static String beginWithB(String wordlist) {
    StringBuilder sb = new StringBuilder();
    String myStr = wordlist;
    for (String b : myStr.split(" ")) {
        if (b.startsWith("b") || b.startsWith("B")) {
            sb.append(b + " ");
        }
    }
    return sb.toString();
}

<强>输出

The list of words is: Batman blueberries bacon burger Batmobile.