OVH Cloud OVH Cloud

Repetition de char dans un string

5 réponses
Avatar
Thierry
Salut,

Comment faire pour compter le nombre de repetition de char dans un
string ? Plus precisement, comment verifier qu'un string ne contient pas
plus de X (par ex X=3) fois le meme char ?

Ex : "abac" ok mais "abaca" pas ok

Merci d'avance
Th.

5 réponses

Avatar
Johann Burkard
Thierry wrote:
Comment faire pour compter le nombre de repetition de char dans un
string ?


public boolean hasLessOccurrences(String s, char c, int x) {
return getOccurrences(s, c) < x;
}

public boolean getOccurrences(String s, char c) {
int occ = 0;
int l = s.length();
for (int i = 0; i < l; ++i) {
if (s.charAt(i) == c) ++occ;
}
return occ;
}

Johann
--
also das ding is schwul und scheiss ohne ende...das is meine meinung.
("Zocker Boulette" in )

Avatar
Fabien
Thierry wrote:
Salut,

Comment faire pour compter le nombre de repetition de char dans un
string ? Plus precisement, comment verifier qu'un string ne contient pas
plus de X (par ex X=3) fois le meme char ?

Ex : "abac" ok mais "abaca" pas ok

Merci d'avance
Th.


Solution de base bourrine :

int cpt=0;
for (int i=0;i<str.length();i++) if (str.charAt(i)=='c') cpt++;
if (cpt>X) { ... } else {...}

@+ Fabien

Avatar
Fabien
Johann Burkard wrote:
Thierry wrote:

Comment faire pour compter le nombre de repetition de char dans un
string ?



public boolean hasLessOccurrences(String s, char c, int x) {
return getOccurrences(s, c) < x;
}

public boolean getOccurrences(String s, char c) {
int occ = 0;
int l = s.length();
for (int i = 0; i < l; ++i) {
if (s.charAt(i) == c) ++occ;
}
return occ;
}

Johann


En effet, c'est bcp plus propre...

@+ Fabien


Avatar
Stéphane Delpech
"Johann Burkard" a écrit dans le message de news:
41b8a29f$0$29836$
Thierry wrote:
Comment faire pour compter le nombre de repetition de char dans un
string ?


public boolean hasLessOccurrences(String s, char c, int x) {
return getOccurrences(s, c) < x;
}

public boolean getOccurrences(String s, char c) {
int occ = 0;
int l = s.length();
for (int i = 0; i < l; ++i) {
if (s.charAt(i) == c) ++occ;
}
return occ;
}

Johann
--


Attention : "public int getOccurrences(...)" au lieu de "public boolean
getOccurrences(...)"

Stéphane


Avatar
Johann Burkard
Stéphane Delpech wrote:
"Johann Burkard" a écrit dans le message de news:
public boolean getOccurrences(String s, char c) {


Attention : "public int getOccurrences(...)" au lieu de "public boolean
getOccurrences(...)"


Oui, j'ai pas vu, merci. :-/

Johann
--
See the different.
(*Tönnes in <a91cm0$105a7p$)