Está en la página 1de 7

DUOC UC

Escuela de Ingeniera

Introduccin a la Programacin

La clase String
Dentro de un objeto de la clases String, Java crea un array de caracteres de una forma similar a como
lo hace el lenguaje C++. A este array se accede a travs de las funciones miembro de la clase.
Los Strings u objetos de la clase String se pueden crear explcitamente o implcitamente. Para crear un
String implcitamente basta poner una cadena de caracteres entre comillas dobles. Por ejemplo, cuando se
escribe:
System.out.println("El primer programa");
Java crea un objeto de la clase String automticamente.
Para crear un String explcitamente escribimos
String str = new String("El primer programa");
Tambin se puede escribir, alternativamente
String str = "El primer programa";
Para crear un String nulo se puede hacer de estas dos formas
String str = "";
String str = new String();
Un String nulo es aqul que no contiene caracteres, pero es un objeto de la clase String. Sin embargo,
String str;
est declarando un objeto str de la clase String, pero an no se ha creado ningn objeto de esta clase.
Cmo se obtiene informacin acerca del String
Una vez creado un objeto de la clase String podemos obtener informacin relevante acerca del objeto a
travs de las funciones miembro.
Para obtener la longitud, nmero de caracteres que guarda un String se llama a la funcin miembro
length.
String str = "El primer programa";
int longitud = str.length();
Podemos conocer si un String comienza con un determinado prefijo, llamando al mtodo startsWith, que
devuelve true o false, segn que el String comience o no por dicho prefijo.
String str = "El primer programa";
boolean resultado = str.startsWith("El");
En este ejemplo la variable resultado tomar el valor true.

Prof. Rigoberto Escobar

La Clase String

1/7

DUOC UC
Escuela de Ingeniera

Introduccin a la Programacin

De modo similar, podemos saber si un String finaliza con un conjunto dado de caracteres, mediante la
funcin miembro endsWith.
String str = "El primer programa";
boolean resultado = str.endsWith("programa");
Si se quiere obtener la posicin de la primera ocurrencia de la letra p, se usa la funcin indexOf.
String str = "El primer programa";
int pos = str.indexOf('p');
Para obtener las sucesivas posiciones de la letra p, se llama a otra versin de la misma funcin
pos = str.indexOf('p', pos+1);
El segundo argumento le dice a la funcin indexOf que empiece a buscar la primera ocurrencia de la
letra p a partir de la posicin pos+1.
Otra versin de indexOf busca la primera ocurrencia de un subString dentro del String.
String str = "El primer programa";
int pos = str.indexOf("pro");
Vemos que una clase puede definir varias funciones miembro con el mismo nombre pero que tienen
distinto nmero de parmetros o de distinto tipo.
Comparacin de Strings
La comparacin de Strings nos da la oportunidad de distinguir entre el operador lgico == y la funcin
miembro equals de la clase String. En el siguiente cdigo
String str1 = "El lenguaje Java";
String str2 = new String("El lenguaje Java");
if(str1 == str2)
{
System.out.println("Los mismos objetos");
}
else
{
System.out.println("Distintos objetos");
}
if(str1.equals(str2))
{
System.out.println("El mismo contenido");
}
else
{
System.out.println("Distinto contenido");
}
Esta porcin de cdigo devolver que str1 y str2 son distintos objetos pero con el mismo contenido. str1
y str2 ocupan posiciones distintas en memoria pero guardan los mismos datos.

Prof. Rigoberto Escobar

La Clase String

2/7

DUOC UC
Escuela de Ingeniera

Introduccin a la Programacin

Cambiemos la segunda sentencia y escribamos


String str1 = "El lenguaje Java";
String str2 = str1;
System.out.prinln("Son el mismo objeto "+(str1 == str2));
Los objetos str1 y str2 guardan la misma referencia al objeto de la clase String creado. La expresin
(str1 == str2) devolver true.
As pues, el mtodo equals compara un String con un objeto cualquiera que puede ser otro String, y
devuelve true cuando dos Strings son iguales o false si son distintos.
String str = "El lenguaje Java";
boolean resultado = str.equals("El lenguaje Java");
La variable resultado tomar el valor true.
La funcin miembro compareTo devuelve un entero menor que cero si el objeto String es menor (en
orden alfabtico) que el String dado, cero si son iguales, y mayor que cero si el objeto String es mayor que el
String dado.
String str = "Toms";
int resultado = str.compareTo("Alberto");
La variable entera resultado tomar un valor mayor que cero, ya que Toms est despus de Alberto en
orden alfabtico.
String str ="Alberto";
int resultado = str.compareTo("Toms");
La variable entera resultado tomar un valor menor que cero, ya que Alberto est antes que Toms en
orden alfabtico.
Extraer un subString de un String
En muchas ocasiones es necesario extraer una porcin o subString de un String dado. Para este
propsito hay una funcin miembro de la clase String denominada subString.
Para extraer un subString desde una posicin determinada hasta el final del String escribimos
String str = "El lenguaje Java";
String subStr = str.subString(12);
Se obtendr el subString "Java".
Una segunda versin de la funcin miembro subString, nos permite extraer un subString especificando
la posicin de comienzo y la el final.
String str = "El lenguaje Java";
String subStr = str.subString(3, 11);
Se obtendr el subString "lenguaje". Recurdese, que las posiciones se empiezan a contar desde cero.

Prof. Rigoberto Escobar

La Clase String

3/7

DUOC UC
Escuela de Ingeniera

Introduccin a la Programacin

Convertir un nmero a String


Para convertir un nmero en String se emplea la funcin miembro esttica valueOf (ms adelante
explicaremos este tipo de funciones).
int valor = 10;
String str = String.valueOf(valor);
La clase String proporciona versiones de valueOf para convertir los datos primitivos: int, long, float,
double.
Esta funcin se emplea mucho cuando programamos applets, por ejemplo, cuando queremos mostrar el
resultado de un clculo en el rea de trabajo de la ventana o en un control de edicin.
Convertir un String en nmero
Cuando introducimos caracteres en un control de edicin a veces es inevitable que aparezcan espacios
ya sea al comienzo o al final. Para eliminar estos espacios tenemos la funcin miembro trim.
String str = " 12 ";
String str1 = str.trim();
Para convertir un String en nmero entero, primero quitamos los espacios en blanco al principio y al
final y luego, llamamos a la funcin miembro esttica parseInt de la clase Integer (clase envolvente que describe
los nmeros enteros)
String str = " 12 ";
int numero = Integer.parseInt(str.trim());
Para convertir un String en nmero decimal (double) se requieren dos pasos: convertir el String en un
objeto de la clase envolvente Double, mediante la funcin miembro esttica valueOf, y a continuacin convertir
el objeto de la clase Double en un tipo primitivo double mediante la funcin doubleValue.
String str = "12.35 ";
double numero = Double.valueOf(str).doubleValue();
Se puede hacer el mismo procedimiento para convertir un String a nmero entero
String str = "12";
int numero = Integer.valueOf(str).intValue();

Prof. Rigoberto Escobar

La Clase String

4/7

DUOC UC
Escuela de Ingeniera

Introduccin a la Programacin

Resumen de Metodos
char charAt(int index)
Returns the character at the specified index.
int compareTo(Object o)
Compares this String to another Object.
int compareTo(String anotherString)
Compares two Strings lexicographically.
int compareToIgnoreCase(String str)
Compares two Strings lexicographically, ignoring case differences.
String concat(String str)
Concatenates the specified String to the end of this String.
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as
the specified StringBuffer.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
Tests if this String ends with the specified suffix.
boolean equals(Object anObject)
Compares this String to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.
void getBytes (int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated. This method does not properly convert characters into bytes. As of
JDK 1.1, the preferred way to do this is via the the getBytes() method, which uses the
platform's default charset.
byte[] getBytes (String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the
result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this String into the destination character array.
int hashCode()
Returns a hash code for this String.
int indexOf(int ch)
Returns the index within this String of the first occurrence of the specified character.
int indexOf (int ch, int fromIndex)
Returns the index within this String of the first occurrence of the specified character,
starting the search at the specified index.
int indexOf (String str)
Returns the index within this String of the first occurrence of the specified subString.

Prof. Rigoberto Escobar

La Clase String

5/7

DUOC UC
Escuela de Ingeniera

Introduccin a la Programacin

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.
String intern()
Returns a canonical representation for the String object.
int lastIndexOf(int ch)
Returns the index within this String of the last occurrence of the specified character.
int lastIndexOf (int ch, int fromIndex)
Returns the index within this String of the last occurrence of the specified character,
searching backward starting at the specified index.
int lastIndexOf (String str)
Returns the index within this String of the rightmost occurrence of the specified
subString.
int lastIndexOf (String str, int fromIndex)
Returns the index within this String of the last occurrence of the specified subString,
searching backward starting at the specified index.
int length()
Returns the length of this String.
boolean matches(String regex)
Tells whether or not this String matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two String regions are equal.
boolean regionMatches (int toffset, String other, int ooffset, int len)
Tests if two String regions are equal.
String replace(char oldChar, char newChar)
Returns a new String resulting from replacing all occurrences of oldChar in this String
with newChar.
String replaceAll(String regex, String replacement)
Replaces each subString of this String that matches the given regular expression with
the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first subString of this String that matches the given regular expression
with the given replacement.
String[] split(String regex)
Splits this String around matches of the given regular expression.
String[] split(String regex, int limit)
Splits this String around matches of the given regular expression.
boolean startsWith(String prefix)
Tests if this String starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if this String starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String subString (int beginIndex)
Returns a new String that is a subString of this String.
String subString(int beginIndex, int endIndex)
Returns a new String that is a subString of this String.

Prof. Rigoberto Escobar

La Clase String

6/7

DUOC UC
Escuela de Ingeniera

Introduccin a la Programacin

char[] toCharArray()
Converts this String to a new character array.
String toLowerCase ()
Converts all of the characters in this String to lower case using the rules of the
default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given
Locale.
String toString()
This object (which is already a String!) is itself returned.
String toUpperCase ()
Converts all of the characters in this String to upper case using the rules of the
default locale.
String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given
Locale.
String trim()

Returns a copy of the String, with leading and trailing whitespace omitted.

static String valueOf(boolean b)


Returns the String representation of the boolean argument.
static String valueOf (char c)
Returns the String representation of the char argument.
static String valueOf (char[] data)
Returns the String representation of the char array argument.
static String valueOf (char[] data, int offset, int count)
Returns the String representation of a specific subarray of the char array argument.
static String valueOf (double d)
Returns the String representation of the double argument.
static String valueOf (float f)
Returns the String representation of the float argument.
static String valueOf (int i)
Returns the String representation of the int argument.
static String valueOf (long l)
Returns the String representation of the long argument.
static String valueOf (Object obj)
Returns the String representation of the Object argument.

Prof. Rigoberto Escobar

La Clase String

7/7

También podría gustarte