2009-10-08 21 views
7

Quale metodo di capitalizzazione è migliore?Stringa maiuscola - modo migliore

miniera:

char[] charArray = string.toCharArray(); 
charArray[0] = Character.toUpperCase(charArray[0]); 
return new String(charArray);

o

Commons Lang - StringUtils.capitalize:

return new StringBuffer(strLen) 
      .append(Character.toTitleCase(str.charAt(0))) 
      .append(str.substring(1)) 
      .toString();

Credo che il mio è meglio, ma vorrei piuttosto chiedere.

+9

Contrastampa: la stringa di maiuscola è davvero il collo di bottiglia nell'applicazione? –

+0

Capisco che non importa così tanto, ma se dovessi scrivere qualsiasi libreria, proverei a farlo funzionare il più bene possibile. – IAdapter

+6

Divertente. Se * I * scrivesse una libreria, proverei a farlo funzionare * nel miglior modo possibile. – Bombe

risposta

2

Le prestazioni sono uguali.

Il codice copia il carattere [] chiamando string.toCharArray() e new String(charArray).

Il codice apache su buffer.append(str.substring(1)) e buffer.toString(). Il codice apache ha un'istanza di stringa aggiuntiva che ha il contenuto di base [1, lunghezza]. Ma questo non verrà copiato quando viene creata la stringa di istanza.

0

Avete programmato entrambi?

Onestamente, sono equivalenti .. quindi quella che esegue meglio per si è il migliore :)

+2

Attenzione che le funzionalità del linguaggio di benchmarking sono molto difficili in Java, vedere questo ottimo articolo di Brian Goetz: http://www.ibm.com/developerworks/java/library/j-jtp12214/index.html?S_TACT=105AGX02&S_CMP=EDU – Jesper

+2

Si noti inoltre che i risultati possono variare in base alla lunghezza della stringa. – Lucero

1

StringBuffer è dichiarato di essere thread-safe, quindi potrebbe essere meno efficace da usare (ma non bisogna scommetterci prima di fare qualche prova pratica).

7

Immagino che la tua versione sarà un po 'più performante, dal momento che non assegna tanti oggetti String temporanei.

prenderei questo (supponendo che la stringa non è vuota):

StringBuilder strBuilder = new StringBuilder(string); 
strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0)))); 
return strBuilder.toString(); 

Tuttavia, si noti che non sono equivalenti dal fatto che si usa toUpperCase() e gli altri usi toTitleCase().

Da un forum post:

Titlecase <> maiuscolo
Unicode definisce tre tipi di caso mappatura: minuscole, maiuscole, e Titlecase. La differenza tra maiuscolo e titlecasing un carattere o carattere sequenza può essere visto nel composto caratteri (cioè, un singolo personaggio che rappresenta una composti ai di due caratteri).

Ad esempio, in Unicode, il carattere U + 01F3 è LATIN SMALL LETTER DZ. (Let scriviamo questo carattere composto usando ASCII come "dz".) Questo carattere
maiuscolo al carattere U + 01F1, LATINA LETTERA DED. (Che è
fondamentalmente "DZ".) Ma titlecases a a carattere U + 01F2, Maiuscolo
lettera D CON PICCOLO lettera Z. (Quale possiamo scrivere "Dz".)

character uppercase titlecase 
--------- --------- --------- 
dz  DZ  Dz 
+0

Potrebbe fornire maggiori dettagli sulla differenza tra toUpperCase() e toTitleCase()? –

+3

Aggiunte alcune informazioni aggiuntive. – Lucero

+1

Il codice Apache è stato probabilmente scritto per 1.4 o prima. Nell'implementazione di Sun, il codice Apache non avrebbe creato alcun array 'char []' temporaneo (sia array Stringsubstring che (inizialmente) 'StringBuffer.toString' condivide gli array di supporto). Quindi il codice Apache sarebbe stato, prima del 2004, più veloce per le grandi stringhe. –

0

Non sono sicuro quale sia la differenza tra toUtilizzoUtente e toTitleCase, ma sembra che la soluzione richieda un'istanza inferiore della classe String, mentre l'implementazione di common lang richiede due (sottostringa e toString creano nuove Stringhe presumo, poiché String è immutabile).

Se questo è "migliore" (immagino tu intenda più veloce) non lo so. Perché non profili entrambe le soluzioni?

1

StringBuilder (da Java 5 in poi) è più veloce di StringBuffer se non è necessario che sia thread-safe, ma come altri hanno detto che è necessario verificare se questo è meglio della soluzione nel tuo caso.

3

Se dovessi scrivere una libreria, proverei ad assicurarmi che il mio Unicode fosse abbastanza preoccupante per le prestazioni. Fuori della parte superiore della mia testa:

int len = str.length(); 
if (len == 0) { 
    return str; 
} 
int head = Character.toUpperCase(str.codePointAt(0)); 
String tail = str.substring(str.offsetByCodePoints(0, 1)); 
return new String(new int[] { head }).concat(tail); 

(. Probabilmente sarei anche guardare la differenza tra il titolo e maiuscole, prima ho commesso)

0

uso questo metodo per la capitalizzazione di spago. la sua totalmente a lavorare senza alcun bug

public String capitalizeString(String value) 
{ 
    String string = value; 
    String capitalizedString = ""; 
    System.out.println(string); 
    for(int i = 0; i < string.length(); i++) 
    { 
     char ch = string.charAt(i); 
     if(i == 0 || string.charAt(i-1)==' ') 
      ch = Character.toUpperCase(ch); 
     capitalizedString += ch; 
    } 
    return capitalizedString; 
} 
0
/** 
    * capitalize the first letter of a string 
    * 
    * @param String 
    * @return String 
    * */ 
    public static String capitalizeFirst(String s) { 
     if (s == null || s.length() == 0) { 
      return ""; 
     } 
     char first = s.charAt(0); 
     if (Character.isUpperCase(first)) { 
      return s; 
     } else { 
      return Character.toUpperCase(first) + s.substring(1); 
     } 
    } 
0

Se capitalizzare solo parole limitate, è meglio cache di esso.

@Test 
public void testCase() 
{ 
    String all = "At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.\n" + 
      "\n" + 
      "A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.\n" + 
      "\n" + 
      "Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.\n" + 
      "\n" + 
      "A shell allows execution of GNU commands, both synchronously and asynchronously. The shell waits for synchronous commands to complete before accepting more input; asynchronous commands continue to execute in parallel with the shell while it reads and executes additional commands. The redirection constructs permit fine-grained control of the input and output of those commands. Moreover, the shell allows control over the contents of commands’ environments.\n" + 
      "\n" + 
      "Shells also provide a small set of built-in commands (builtins) implementing functionality impossible or inconvenient to obtain via separate utilities. For example, cd, break, continue, and exec cannot be implemented outside of the shell because they directly manipulate the shell itself. The history, getopts, kill, or pwd builtins, among others, could be implemented in separate utilities, but they are more convenient to use as builtin commands. All of the shell builtins are described in subsequent sections.\n" + 
      "\n" + 
      "While executing commands is essential, most of the power (and complexity) of shells is due to their embedded programming languages. Like any high-level language, the shell provides variables, flow control constructs, quoting, and functions.\n" + 
      "\n" + 
      "Shells offer features geared specifically for interactive use rather than to augment the programming language. These interactive features include job control, command line editing, command history and aliases. Each of these features is described in this manual."; 
    String[] split = all.split("[\\W]"); 

    // 10000000 
    // upper Used 606 
    // hash Used 114 

    // 100000000 
    // upper Used 5765 
    // hash Used 1101 

    HashMap<String, String> cache = Maps.newHashMap(); 

    long start = System.currentTimeMillis(); 
    for (int i = 0; i < 100000000; i++) 
    { 

     String upper = split[i % split.length].toUpperCase(); 

//   String s = split[i % split.length]; 
//   String upper = cache.get(s); 
//   if (upper == null) 
//   { 
//    cache.put(s, upper = s.toUpperCase()); 
// 
//   } 
    } 
    System.out.println("Used " + (System.currentTimeMillis() - start)); 
} 

Il testo è selezionato da here.

Attualmente, ho bisogno di scrivere in maiuscolo il nome e le colonne della tabella, molte più volte, ma sono limitati. Se usi hashMap, la cache sarà migliore.

:-)

Problemi correlati