1. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Java Cheat Sheet
Documentação oficial
String
Prof. Rafael Liberato
// Declaração e atribuição
String x1 = " U T F P R ";
String x2 = new String( " U T F P R ");
System.out.println(x1 == x2); // false
//Literal String == Objeto Anônimo
System.out.println( " J a v a "); // Objeto Anônimo
System.out.println( " J a v a ".length()); //4
// Otimização de Memória
String s1 = " J a v a ";
String s2 = " J a v a ";
System.out.println(s1 == s2); // true
A cada concatenação ou modificação é criado um novo objeto.
O objeto referenciado NUNCA é alterado (IMUTÁVEL)
Alternativa: StringBuilder
2
s1
s2
Um objeto String
é
Um objeto String
é imutável
int n1 = 10, n2 = 20;
System.out.println( " > > 1 0 + 2 0 = " + n1 + n2 );
System.out.println( " > > 1 0 + 2 0 = " + ( n 1 + n 2 ));
System.out.println(2+2+2 + "==" + 3+3); //6==33
String()
String(byte[] bytes)
String(byte[] bytes, String charsetName)
String(byte[] bytes, Charset charset)
String(byte[] bytes, int offset, int length)
String(byte[] bytes, int offset, int length,
Charset charset)
String(byte[] bytes, int offset, int length,
String charsetName)
String(char[] value)
String(char[] value, int offset, int count)
String(String original)
String(StringBuffer buffer)
String(StringBuilder builder)
v1.0
Objetos Imutáveis
PRINCIPAIS MÉTODOS
*Nenhum método altera o conteúdo da String (Imutável)
Exemplos
* cuidado com as concatenações
Concatenar ou Somar ?
Se um dos operandos for uma String então concatena, senão soma.
Construtores
boolean equals(Object obj)
boolean equalsIgnoreCase(String s2)
int compareTo(String s2)
int compareToIgnoreCase(String s2)
boolean regionMatches(int inicio, String s2, int inicioS2, int qtde)
boolean startsWith(String prefixo)
boolean startsWith(String prefixo, int inicio)
boolean endsWith(String sufixo)
boolean contains(String substring)
int indexOf(String str)
int indexOf(String str, int posInicial)
int lastIndexOf(String str)
int lastIndexOf(String str, int posInicial)
char charAt(int pos)
String substring(int posInicial)
String substring(int posInicial, int posFinal)
String replace(String old, String new)
int length()
String trim()
String toUpperCase()
String toLowerCase()
char[] toCharArray()
String valueOf(tipos primitivos)
String[] split()
s1 = " U m o b j e t o S t r i n g é ";
s2 = s1;
s2 += " i m u t á v e l ";
System.out.println(s1);
System.out.println(s2);
x1
x2
UTFPR
UTFPR
s1
s2
Java
Cria 100 novos objetos
s1
0
01
012
1
s1
s2
Um objeto String
é
Comparando
String
Localizando
em uma String
Extraindo
e substituíndo
Utilitários
String s1 = " u t f p r C a m p o M o u r ã o ";
String s2 = new String( " U t f p r C a m p o M o u r ã o ");
(s1 == s2) false
s1.equals(s2) false
s2.equals(s1) false
s1.equalsIgnoreCase(s2) true
s1.compareTo(s2) 32
s2.compareTo(s1) -32
s2.compareToIgnoreCase(s1) 0
s1.regionMatches(1, s2, 1, 3) true
s1.startsWith( " u ") true
s1.startsWith( " C a m p o ",6) true
s1.endsWith( " p r ") false
s1.contains( " C a m p o ") true
s1.indexOf( " r ") 4
s1.indexOf( " r ",5) 15
s1.lastIndexOf( " r ") 15
s1.lastIndexOf( " r ",14) 4
s1.indexOf( " A ") -1
s1.charAt(0) "u"
s1.charAt(s1.length() - 1) "o"
s1.substring(6) "Campo Mourão"
s1.substring(0,3) "utf"
s1.replace( " o ", " @ ") "utfpr Camp@ M@urã@"
Conversões
int Integer.parseInt( " 1 5 ")
double Double.parseDouble( " 3 . 1 4 ")
String
float Float.parseFloat( " 1 . 2 F ")
Boolean.parseBoolean( " t r u e ")
boolean
String De qualquer
tipo primitivo ou
String.valueOf( 2)
3.14 + ""
* nos exemplos acima os literais podem ser
substituídos por variáveis do mesmo tipo.
Por Rafael Liberato Roberto . Este trabalho foi licenciado com uma Licença
Creative Commons - Atribuição-Uso não-comercial-Compartilhamento pela mesma licença
for(int cont=0; cont<100; cont++){
s1+=cont;
}
System.out.println(s1);
2. (StringBuilder) MUTÁVEL versus IMUTÁVEL (String)
String s = new String( " U T F P R ");
String sb = new StringBuilder( " U T F P R ");
//Concatenando
s += "-CM";
sb.append( " - C M ");
//Substituindo
s.replace( " C M ", " L D ");
sb.replace( " C M ", " L D ");
Teste de desempenho
Construtores
*valores de uma máquina específica
String.format( " O v a l o r d e % s é % . 2 f ", " P I ", 3.14);
System.out.printf( " O v a l o r d e % s é % . 2 f ", " P I ", 3.14);
%c character
%d decimal (integer) number (base 10)
%e exponential floating-point number
%f floating-point number
%i integer (base 10)
%o octal number (base 8)
%s a string of characters
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
printf( " ' % 5 d ' ", 10) ' 10'
printf( " ' % - 5 d ' ", 10) '10 '
printf( " ' % 0 5 d ' ", 10) '00010'
printf( " ' % 0 5 d ' ", -10) '-0010'
printf( " ' % + 5 d ' ", 10) ' +10'
printf( " ' % - + 5 d ' ", 10) '+10 '
printf( " ' % . 1 f ' ", 10.3456) '10,3'
printf( " ' % . 2 f ' ", 10.3456) '10,35'
printf( " ' % 8 . 2 f ' ", 10.3456) ' 10,35'
printf( " ' % - 8 . 2 f ' ", 10.3456) '110,35'
printf( " ' % 0 8 . 2 f ' ", 10.3456) '00010,35'
printf( " ' % 8 . 6 f ' ", 10.3456) '10,345600'
printf( " ' % s ' ", " J a v a ") 'Java'
printf( " ' % 1 0 s ' ", " J a v a ") ' Java'
printf( " ' % - 1 0 s ' ", " J a v a ") 'Java '
String
StringBuilder sb2 = new StringBuilder(str)
StringBuilder
Modificando
1
Analisando Strings
Por Rafael Liberato Roberto . Este trabalho foi licenciado com uma Licença
Creative Commons - Atribuição-Uso não-comercial-Compartilhamento pela mesma licença
StringBuilder
StringBuilder()
StringBuilder(String str)
s
sb
UTFPR
UTFPR-CM
UTFPR-CM
s
sb
UTFPR-CM
UTFPR-LD
UTFPR-LD
Conversões
StringBuilder sb1 = new StringBuilder( " 1 5 ")
String s1 = new String(sb1)
String s2 = sb1.toString()
String s3 = String.valueOf(sb1)
tamanho = 10000;
String sb = new StringBuilder();
for (int i = 0; i < t a m a n h o ; i++) {
sb.append(i);
}
String s = new String();
for (int i = 0; i < t a m a n h o ; i++) {
s+= i;
}
String[] palavras = texto. s p l i t( " ");
for(String palavra : palavras){
System.out.println(palavra);
}
StringTokenizer s T o k e n = n e w S t r i n g T o k e n i z e r (texto);
while(sToken.hasMoreTokens()){
System.out.println(sToken.nextToken());
}
Scanner s c a n n e r = n e w S c a n n e r (texto);
while(scanner.hasNext()){
System.out.println(scanner.next());
}
Tamanho SBuider String
100 1 2
1.000 3 25
10.000 7 1.722
100.000 22 453.730
milessegundos
StringBuilder
String
PRINCIPAIS MÉTODOS
Alteram a sequência de caracteres do objeto (MUTÁVEL)
int indexOf(String str)
int indexOf(String str, int posInicial)
int lastIndexOf(String str)
int lastIndexOf(String str, int posInicial)
char charAt(int pos)
String substring(int posInicial)
String substring(int posInicial, int posFinal)
StringBuilder replace(int inicio, int fim, String str)
void setCharAt(int pos, char c)
StringBuilder delete(int inicio, int fim)
char deleteCharAt()
StringBuilder append(String str)
StringBuilder insert(int pos, String str)
StringBuilder reverse()
String toString()
Localizando
em uma String
Extraindo
e substituíndo
Utilitários
Exemplos
String sb = new StringBuilder("UTFPR-CM");
sb.replace(6, 8, " C a m p o M o u r ã o ") UTFPR-Campo Mourão
sb.setCharAt(7, ' @ ') UTFPR-C@mpo Mourão
sb.delete(5, sb.length()) UTFPR
sb.deleteCharAt(1) UFPR
sb.insert(1, " T ") UTFPR
sb.append( " - C M ") UTFPR-CM
sb.reverse() MC-RPFTU
Método split
StringTokenizer
Scanner
2
3
Alterando o delimitador
String[] palavras = texto. s p l i t( " ; ")
StringTokenizer s T o k e n = n e w S t r i n g T o k e n i z e r (texto, " ; ")
scanner.useDelimiter( " ; ")
1
2
3
Formatando String
"O valor de PI é 3,14"
Caracteres para formatação
Exemplos