[英]Count of substrings within string
我的程序應該執行以下操作:
我不應該使用 .str,而是創建我自己的方法。
天真的方法(在每個可能的索引處檢查子字符串)以O(nk ) 運行,其中n是字符串的長度, k是子字符串的長度。 這可以用 for 循環來實現,比如haystack.substring(i).startsWith(needle)
。
但是,存在更有效的算法。 您可能想看看Knuth-Morris-Pratt 算法或Aho-Corasick 算法。 與天真的方法相反,這兩種算法在輸入時也表現良好,例如“在 10000 個 'X' 的字符串中查找 100 個 'X' 的子字符串。
只需替換第一次出現並計數,直到沒有出現。
int count = 0;
while (str.indexOf(subStr)>-1){
str = str.replaceFirst(subStr, "");
count++;
}
return count ;
這是我的代碼....
import java.util.Scanner;
public class occurrenceOf_Substring {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println(" Enter a string");
String str=input.nextLine();
System.out.println(" Enter a substring");
String substring=input.nextLine();
int l=substring.length();
int count=0;
int index=str.indexOf(substring); // To find first occurrence
while(index<str.length() && index != -1)
{
index=str.indexOf(substring,index+l);/// to find next occurrences
count=count+1;
}
System.out.println("substrin count is "+count);
} }
算法:
步驟 1:將主字符串轉換為字符數組
步驟 2:將子字符串轉換為字符數組
第 3 步:逐個字符比較兩個數組
步驟4:如果子串數組中至少有一個字符與主串字符數組不匹配,則從子串的第一個字符開始,但在主串中繼續移動
第 5 步:如果子字符串的所有字符都匹配,則增加計數並再次從子字符串的第一個位置開始,就是這樣。
import java.io.*;
import java.util.Scanner;
public class SubStringCount {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
System.out.println("Enter you Main string:");
String mainstring=input.nextLine();
System.out.println("Enter the substring");
String substring=input.nextLine();
int i=0;int j=0;
char[] str=mainstring.toCharArray(); // converting main string to character array
char[] sub=substring.toCharArray(); // converting substring to character array
int count=0;
while(i<str.length)
{
if(str[i]==sub[j])
{
j++;
}
else
{
j=0;
}
if(j==sub.length)
{
j=0;
count++;
}
i++;
}
char
值序列(如數組)true
,則增加您的計數器。這是基本算法。 如果您已啟動並運行它,請考慮特殊情況,例如源字符串為空或比模式短。
在一行中:
int count = (str.length() - str.replace(subStr, "").length()) / subStr.length();
另一個單行可能是:使用split("sep", -1)
,然后你有數組長度(-1)。
例子:
String input = "@human@mail@@com@";
String search = "@";
int occurrences = input.split(search, -1).length - 1;
說明: split
用給定的分隔符(正則表達式)分割輸入字符串。 所以它返回一個包含分隔符之間的子字符串的數組。 第二個參數-1
告訴 split 不以任何方式限制數組長度。 如果 split 與默認限制 (0) 一起使用,尾隨空字符串將被丟棄(-> 如果要搜索的字符串在末尾,則結果錯誤)。 所以為了最終得到搜索字符串的出現次數,數組長度必須減少 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.