编写一个程序,要求用户输入两个字符串,并打印第二个字符串出现在第一个字符串中的次数。例如,如果第一个String是“banana”而第二个是“an”,则程序将打印2。
以下是我目前的代码
public class Assignment4 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
当我在第一个字符串中键入banana时,第二个字符串是“an”时,唯一出现的是数字3,它是出现3次的字符a,但不是2,因为它假设只有2“一个“
答案 0 :(得分:0)
考虑一下我多年前学到的这个技巧:
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
输入香蕉且一个将打印2