2012-09-07 114 views
5

我需要输入一个两个字符串,第一个字符串是任何字,第二个字符串是前一个字符串的一部分,我需要输出字符串的次数第二个发生。例如:String 1 = CATSATONTHEMAT String 2 = AT。输出将是3,因为AT在CATSATONTHEMAT中发生三次。这里是我的代码:获取一个字符串在另一个字符串中出现的次数

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    String word8 = sc.next(); 
    String word9 = sc.next(); 
    int occurences = word8.indexOf(word9); 
    System.out.println(occurences); 
} 

,当我使用此代码,它输出1

+1

'indexOf'不返回计数,它返回第一次出现的位置。 [Javadocs](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) – Brian

+2

准确地复制到字符串:http ://stackoverflow.com/questions/12309109/comparing-a-substring-to-a-string-in-java – JTMon

+0

@Brian这就是为什么他要求帮助。反正,正则表达式来拯救? –

回答

3

您也可以尝试:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    String word8 = sc.nextLine(); 
    String word9 = sc.nextLine(); 
    int index = word8.indexOf(word9); 
    sc.close(); 
    int occurrences = 0; 
    while (index != -1) { 
     occurrences++; 
     word8 = word8.substring(index + 1); 
     index = word8.indexOf(word9); 
    } 
    System.out.println("No of " + word9 + " in the input is : " + occurrences); 
} 
+1

啊我没有看到while循环部分非常感谢。 – Eric

+1

不要忘记关闭扫描仪。 – arshajii

11

有趣的解决方案:

public static int countOccurrences(String main, String sub) { 
    return (main.length() - main.replace(sub, "").length())/sub.length(); 
} 

基本上我们在这里所做的是减去main从删除的sub所有实例main产生的字符串的长度长度是什么 - 我们再经除以这个数字确定sub被删除的次数为sub,给出我们的答案。那么到底

你有这样的事情:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    String word8 = sc.next(); 
    String word9 = sc.next(); 
    int occurrences = countOccurrences(word8, word9); 
    System.out.println(occurrences); 

    sc.close(); 
} 
+1

+1有趣的部分:) – JTMon

+1

聪明:)但['.replace'](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace%28java .lang.CharSequence,%20java.lang.CharSequence%29)会更好,因为它不使用像'.replaceAll'这样的正则表达式,并且它具有与您使用它相同的语义。 – Brian

+0

是的好点 - 修复。 – arshajii

0

另一种选择:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 

    String word8 = sc.next(); 
    String word9 = sc.next(); 
    int occurences = word8.split(word9).length; 
    if (word8.startsWith(word9)) occurences++; 
    if (word8.endsWith(word9)) occurences++; 
    System.out.println(occurences); 

    sc.close(); 
} 

startsWithendsWith需要因为split()省略了尾随的空字符串。

1

为什么没有人发布最明显,最快速的解决方案?

int occurrences(String str, String substr) { 
    int occurrences = 0; 
    int index = str.indexOf(substr); 
    while (index != -1) { 
     occurrences++; 
     index = str.indexOf(substr, index + 1); 
    } 
    return occurrences; 
} 
相关问题