Zliczanie wystąpień danego ciągu w zdaniu

0

Staram się rozwiązać zadanie którego celem jest wypisanie liczby wystąpień podanego ciągu w całym zdaniu, doszedłem do pewnego momentu:

package zad_5_10;

import java.util.Scanner;


public class Zad_5_10 {

    public static void main(String[] args) {
        Scanner dane = new Scanner(System.in);
        System.out.print("Podaj zdanie: ");
        String zdanie = dane.nextLine();
        
        System.out.print("Podaj szukaną frazę: ");
        String szukane = dane.nextLine();
        
        int liczbaWystapien = strFindAndCount(zdanie, szukane);
        System.out.println("Liczba wystąpien szukanej frazy w zdaniu = " + liczbaWystapien);
    }
    
    public static int strFindAndCount(String gdzie, String co)
    {
        int licznikWystapien = 0;
        String[] tablicaSlow = new String[200];
        tablicaSlow = gdzie.split("\\s+");
        
        for (int i = 0 ; i < tablicaSlow.length;i++)
        {
            
            if(tablicaSlow[i].contains(co))
            {
                licznikWystapien++;                         
            }
            
        }
        return licznikWystapien;
    }
    
}

Wszystko jest okej do momentu w którym nie podam zdania 'mama ma kota' i liczę wystąpienia ciągu 'ma', wynik otrzymuje 2 a prawidłowa odpowiedź to 3 ponieważ w słowie 'mama', ciąg 'ma' występuje dwa razy, jeśli mógłbym prosić o podanie chociaż sposobu w jaki zliczyć ilość wystąpień danego ciągu w jednym słowie było by super.

1

Użyj metody indexOf(string, int) w pętli - będziesz potrzebował zmiennej lokalnej, która będzie trzymała indeks ostatniego wystapienia szukanej frazy. Po znalezieniu frazy wywołujesz w nastepnej interacji indexOf z indeksem będącym rezultatem poprzedniego wywołania indexOf powiększonym o 1 (żeby nie kręcić się w miejscu). Pętle przerywasz gdy indexOf zwróci -1.

0

Możesz użyć metody subSequence:

    static int findSubstringOccurences(String s, String p) {
        int cnt = 0;
        for (int i = 0; i < s.length() - p.length() + 1; ++i) {
            if (s.subSequence(i, i + p.length()).equals(p))
                ++cnt;
        }
        return cnt;
    }

    public static void main(String [] args) {
        System.out.println(findSubstringOccurences("mama ma kotama", "ma")); // -> 4
    }
2

Proponuję żebyś dopisał jakieś unit testy, będzie Ci łatwiej.
Coś zrobione na szybko:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	
    public static int strFindAndCount(String gdzie, String co)
    {
        int licznikWystapien = 0;
        String[] tablicaSlow = new String[200];
        tablicaSlow = gdzie.split("\\s+");

        for (int i = 0 ; i < tablicaSlow.length;i++)
        {

            if(tablicaSlow[i].contains(co))
            {
                licznikWystapien++;                         
            }

        }
        return licznikWystapien;
    }

    public static int strFindAndCount2(String gdzie, String co)
    {
    	if (co.length() <= 0 || gdzie.length() < co.length()) {
    		return 0;
    	}
    	
        int licznikWystapien = 0;
        int idx = 0;
        
        while(idx >= 0 && (idx + co.length() <= gdzie.length())) {
        	idx = gdzie.indexOf(co, idx);
        	if (idx >= 0) {
        		licznikWystapien++;
        		idx++;
        	} 
        }
        return licznikWystapien;
    }
    
    private static void test(int testId, int methodId, String text, String pattern, int expected) {
      int result;
      
      if (methodId == 1) {
      	result = strFindAndCount(text, pattern);
      } else {
      	result = strFindAndCount2(text, pattern);
      }	
      
      if (result == expected) {
      	System.out.printf("Test %d, method %d: OK%n", testId, methodId);
      } else {
      	System.out.printf("Test %d, method %d: failed, expected: %d, result: %d%n", testId, methodId, expected, result);
      }
    }

    private static void test(int testId, String text, String pattern, int expected) {
    	test(testId, 1, text, pattern, expected);
    	test(testId, 2, text, pattern, expected);
    }
    
	public static void main (String[] args) throws java.lang.Exception
	{
		test(1, "mama ma kota", "ma", 3);
		test(2, "mama ma kota", "", 0);
		test(3, "", "", 0);
		test(4, "mama", "mama", 1);
		test(5, "ma", "mama", 0);
		test(6, "mama", "m", 2);
		test(7, "mama, mamma mia", "ma", 4);
		test(8, "maaa, mia", "aa", 2);
   }
}

Wynik:
https://ideone.com/CnXHEa

Test 1, method 1: failed, expected: 3, result: 2
Test 1, method 2: OK
Test 2, method 1: failed, expected: 0, result: 3
Test 2, method 2: OK
Test 3, method 1: failed, expected: 0, result: 1
Test 3, method 2: OK
Test 4, method 1: OK
Test 4, method 2: OK
Test 5, method 1: OK
Test 5, method 2: OK
Test 6, method 1: failed, expected: 2, result: 1
Test 6, method 2: OK
Test 7, method 1: failed, expected: 4, result: 2
Test 7, method 2: OK
Test 8, method 1: failed, expected: 2, result: 1
Test 8, method 2: OK

1 użytkowników online, w tym zalogowanych: 0, gości: 1