这是主要的:
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);
}
}
所有方法都在另一个类中。我在为lastWithB方法苦苦挣扎。我还有其他工作。到目前为止,我对这种方法的了解:
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”开头的单词返回到主要内容。有任何想法吗? (是的,我必须这样做)。
最佳答案
您的方法对我来说看起来不错,您只需要在返回String时创建一个字符串即可。 (请参见下面的代码)
码
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.
关于java - 查找/打印以特定字母开头的特定单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40861070/