Diskuze: Java string() - dotaz
V předchozím kvízu, Online test znalostí Java, jsme si ověřili nabyté zkušenosti z kurzu.
Zobrazeno 2 zpráv z 2.
V předchozím kvízu, Online test znalostí Java, jsme si ověřili nabyté zkušenosti z kurzu.
Ahoj, hádam, že keď už mesiac robíte so Stringami tak ste preberali aj metódy ako indexOf, subString, length atď.
//todo kontrola na null alebo prazdne Stringy
public static int getSubstringOccurrenceCount(String stringWhereSearch, String stringWhatSearch){
int count = 0;
int offset = 0;
while(true){
offset = stringWhereSearch.indexOf(stringWhatSearch, offset);
if(offset == -1){
break;
}
count++;
offset += stringWhatSearch.length();
}
return count;
}
Tebe bude stačiť zavolať
System.out.println(getSubstringOccurrenceCount(s1, s2));
V podstate len skracuješ danú vetu v ktorej hľadáš od toho indexu ktorý ti vráti metóda indexOf + dĺžka toho stringu ktorý hľadáš.
java.lang.String
public int indexOf(String str,
int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
The returned index is the smallest value k for which:
k >= fromIndex && this.startsWith(str, k)If no such value of k exists, then -1 is returned.
Parameters:
str - the substring to search for.
fromIndex - the index from which to start the search.
Returns:
the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.
Zobrazeno 2 zpráv z 2.