Découper les personnages en Java

Comment puis-je découper des caractères en Java?
par exemple

Ssortingng j = “\joe\jill\”.Trim(new char[] {“\”}); 

j devrait être

“Joe \ Jill”

 Ssortingng j = “jack\joe\jill\”.Trim("jack"); 

j devrait être

“\ joe \ jill \”

etc

Apache Commons a une excellente classe SsortingngUtils . Dans SsortingngUtils il existe une méthode ssortingp(Ssortingng, Ssortingng) qui fera ce que vous voulez.

Je recommande fortement d’utiliser Apache Commons, en particulier les bibliothèques Collections et Lang.

Cela fait ce que vous voulez:

 public static void main (Ssortingng[] args) { Ssortingng a = "\\joe\\jill\\"; Ssortingng b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", ""); System.out.println(b); } 

Le $ est utilisé pour supprimer la séquence à la fin de la chaîne. Le ^ est utilisé pour enlever au début.

Vous pouvez également utiliser la syntaxe suivante:

 Ssortingng b = a.replaceAll("\\\\$|^\\\\", ""); 

Le | signifie “ou”.

Dans le cas où vous voulez couper d’autres caractères, adaptez simplement la regex:

 Ssortingng b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining 

CharMatcher – Google Guava

Dans le passé, je répondais à Apache commins-lang de Colins . Mais maintenant que les librairies de Google sont disponibles, la classe CharMatcher fera ce que vous voulez:

 Ssortingng j = CharMatcher.is('\\').sortingmFrom("\\joe\\jill\\"); // j is now joe\jill 

CharMatcher dispose d’un ensemble très simple et puissant d’API ainsi que de constantes prédéfinies qui facilitent la manipulation. Par exemple:

 CharMatcher.is(':').countIn("a:b:c"); // returns 2 CharMatcher.isNot(':').countIn("a:b:c"); // returns 3 CharMatcher.inRange('a', 'b').countIn("a:b:c"); // returns 2 CharMatcher.DIGIT.retainFrom("a12b34"); // returns "1234" CharMatcher.ASCII.negate().removeFrom("a®¶b"); // returns "ab"; 

Très belles choses.

Voici une autre solution non-regexp, non super géniale, non super optimisée, mais très facile à comprendre:

 public static Ssortingng sortingmSsortingngBySsortingng(Ssortingng text, Ssortingng sortingmBy) { int beginIndex = 0; int endIndex = text.length(); while (text.subssortingng(beginIndex, endIndex).startsWith(sortingmBy)) { beginIndex += sortingmBy.length(); } while (text.subssortingng(beginIndex, endIndex).endsWith(sortingmBy)) { endIndex -= sortingmBy.length(); } return text.subssortingng(beginIndex, endIndex); } 

Usage:

 Ssortingng sortingmmedSsortingng = sortingmSsortingngBySsortingng(ssortingngToTrim, "/"); 

Vous pouvez utiliser removeStart et removeEnd d’Apache Commons Lang SsortingngUtils

Fait à la main pour la première option:

 public class Rep { public static void main( Ssortingng [] args ) { System.out.println( sortingmChar( '\\' , "\\\\\\joe\\jill\\\\\\\\" ) ) ; System.out.println( sortingmChar( '\\' , "joe\\jill" ) ) ; } private static Ssortingng sortingmChar( char toTrim, Ssortingng inSsortingng ) { int from = 0; int to = inSsortingng.length(); for( int i = 0 ; i < inString.length() ; i++ ) { if( inString.charAt( i ) != toTrim) { from = i; break; } } for( int i = inString.length()-1 ; i >= 0 ; i-- ){ if( inSsortingng.charAt( i ) != toTrim ){ to = i; break; } } return inSsortingng.subssortingng( from , to ); } } 

Des tirages

joe\jil

joe\jil

il semble qu’il n’y ait pas de java api prêt à être utilisé, mais vous pouvez écrire une méthode pour le faire pour vous. ce lien pourrait être utile

EDIT : modifié par la réponse pour ne remplacer que le premier et le dernier caractère ‘\’.

 System.err.println("\\joe\\jill\\".replaceAll("^\\\\|\\\\$", "")); 

J’écrirais en fait ma propre petite fonction qui fait l’affaire en utilisant un vieil access aux caractères:

 public static Ssortingng sortingmBackslash( Ssortingng str ) { int len, left, right; return str == null || ( len = str.length() ) == 0 || ( ( left = str.charAt( 0 ) == '\\' ? 1 : 0 ) | ( right = len > left && str.charAt( len - 1 ) == '\\' ? 1 : 0 ) ) == 0 ? str : str.subssortingng( left, len - right ); } 

Cela se comporte de la même manière que Ssortingng.sortingm (), mais il fonctionne uniquement avec “\” au lieu de l’espace.

Voici une alternative qui fonctionne et utilise réellement sortingm (). 😉 Althogh ce n’est pas très efficace, il va probablement battre toutes les approches basées sur l’expression rationnelle.

 Ssortingng j = “\joe\jill\”; j = j.replace( '\\', '\f' ).sortingm().replace( '\f', '\\' ); 

Je ne pense pas qu’il y ait une fonction intégrée pour ajuster en fonction d’une chaîne passée. Voici un petit exemple de la façon de procéder. Ce n’est probablement pas la solution la plus efficace, mais elle est probablement assez rapide pour la plupart des situations, elle peut être évaluée et adaptée à vos besoins. Je recommande de tester les performances et l’optimisation en fonction des besoins pour tout extrait de code qui sera utilisé régulièrement. Ci-dessous, j’ai inclus des informations de synchronisation comme exemple.

 public Ssortingng sortingm( Ssortingng ssortingngToTrim, Ssortingng ssortingngToRemove ) { Ssortingng answer = ssortingngToTrim; while( answer.startsWith( ssortingngToRemove ) ) { answer = answer.subssortingng( ssortingngToRemove.length() ); } while( answer.endsWith( ssortingngToRemove ) ) { answer = answer.subssortingng( 0, answer.length() - ssortingngToRemove.length() ); } return answer; } 

Cette réponse suppose que les caractères à découper sont une chaîne. Par exemple, passer “abc” va supprimer “abc” mais pas “bbc” ou “cba”, etc.

Quelques temps de performance pour exécuter chacun des 10 millions de fois suivants.

" mile ".sortingm(); s’exécute en 248 ms inclus en tant qu’implémentation de référence pour les comparaisons de performances.

sortingm( "smiles", "s" ); s’exécute en 547 ms – environ 2 fois plus longtemps que la méthode Ssortingng.sortingm() de java.

"smiles".replaceAll("s$|^s",""); s’exécute en 12 306 ms – environ 48 fois plus longtemps que la méthode Ssortingng.sortingm() de java.

Et en utilisant un modèle de regex compilé Pattern pattern = Pattern.comstack("s$|^s"); pattern.matcher("smiles").replaceAll(""); s’exécute en 7 804 ms – environ 31 fois plus longtemps que la méthode Ssortingng.sortingm() de java.

Voici comment je le ferais.

Je pense que c’est à peu près aussi efficace que possible. Il optimise la casse à un seul caractère et évite de créer plusieurs sous-chaînes pour chaque sous-séquence supprimée.

Notez que le cas en coin du passage d’une chaîne vide à l’assiette est traité (certaines des autres réponses entreraient dans une boucle infinie).

 /** Trim all occurrences of the ssortingng rmvval from the left and right of src. Note that rmvval constitutes an entire ssortingng which must match using Ssortingng.startsWith and Ssortingng.endsWith. */ static public Ssortingng sortingm(Ssortingng src, Ssortingng rmvval) { return sortingm(src,rmvval,rmvval,true); } /** Trim all occurrences of the ssortingng lftval from the left and rgtval from the right of src. Note that the values to remove constitute ssortingngs which must match using Ssortingng.startsWith and Ssortingng.endsWith. */ static public Ssortingng sortingm(Ssortingng src, Ssortingng lftval, Ssortingng rgtval, boolean igncas) { int str=0,end=src.length(); if(lftval.length()==1) { // optimize for common use - sortingmming a single character from left char chr=lftval.charAt(0); while(str1) { // handle repeated removal of a specific character sequence from left int vallen=lftval.length(),newstr; while((newstr=(str+vallen))<=end && src.regionMatches(igncas,str,lftval,0,vallen)) { str=newstr; } } if(rgtval.length()==1) { // optimize for common use - trimming a single character from right char chr=rgtval.charAt(0); while(str1) { // handle repeated removal of a specific character sequence from right int vallen=rgtval.length(),newend; while(str<=(newend=(end-vallen)) && src.regionMatches(igncas,newend,rgtval,0,vallen)) { end=newend; } } if(str!=0 || end!=src.length()) { if(str
 public static Ssortingng sortingm(Ssortingng value, char c) { if (c <= 32) return value.trim(); int len = value.length(); int st = 0; char[] val = value.toCharArray(); /* avoid getfield opcode */ while ((st < len) && (val[st] == c)) { st++; } while ((st < len) && (val[len - 1] == c)) { len--; } return ((st > 0) || (len < value.length())) ? value.substring(st, len) : value; }