Operações comuns de strings em Java

Operações comuns de strings em Java

1. Introdução

Valores e operações baseados em string são bastante comuns no desenvolvimento diário, e qualquer desenvolvedor Java deve ser capaz de lidar com eles.

Neste tutorial, forneceremos uma folha de referência rápida de operaçõesString comuns.

Além disso, vamos lançar alguma luz sobre as diferenças entreequals e “==” e entreStringUtils#isBlank areia #isEmpty.

2. Transformando um Char em uma String

Umchar representa um caractere em Java. Mas na maioria dos casos, precisamos de umString.

Então, vamos começar transformandochars emStrings _: _

String toStringWithConcatenation(final char c) {
    return String.valueOf(c);
}

3. Anexando strings

Outra operação frequentemente necessária é anexar strings com outros valores, comochar:

String appendWithConcatenation(final String prefix, final char c) {
    return prefix + c;
}

Podemos anexar outros tipos básicos comStringBuilder também:

String appendWithStringBuilder(final String prefix, final char c) {
    return new StringBuilder(prefix).append(c).toString();
}

4. Obtendo um personagem por índice

Se precisarmos extrair um caractere de uma string, a API fornecerá tudo o que queremos:

char getCharacterByIndex(final String text, final int index) {
    return text.charAt(index);
}

Como aString usachar[] como uma estrutura de dados de apoio,the index starts at zero.

5. Manipulando valores ASCII

Podemos facilmente alternar entre umchar e sua representação numérica (ASCII) lançando:

int asciiValue(final char character) {
    return (int) character;
}

char fromAsciiValue(final int value) {
    Assert.isTrue(value >= 0 && value < 65536, "value is not a valid character");
    return (char) value;
}

Obviamente, comoint tem 4 bytes sem sinal echar tem 2 bytes sem sinal, precisamos verificar se estamos trabalhando com valores de caracteres legais.

6. Removendo todo o espaço em branco

Às vezes, precisamos nos livrar de alguns caracteres, geralmente espaços em branco. Agood way is to use the replaceAll method with a regular expression:

String removeWhiteSpace(final String text) {
    return text.replaceAll("\\s+", "");
}

7. Associando coleções a uma string

Outro caso de uso comum é quando temos algum tipo deCollectione queremos criar uma string a partir dele:

 String fromCollection(final Collection collection) {
   return collection.stream().map(Objects::toString).collect(Collectors.joining(", "));
}

Observe queCollectors.joining permitespecifying the prefix or the suffix.

8. Dividindo uma String

Ou, por outro lado, podemos dividir uma string por um delimitador usando o métodosplit:

String[] splitByRegExPipe(final String text) {
   return text.split("\\|");
}

Novamente, estamos usando uma expressão regular aqui, desta vez para dividir por um tubo. Como queremos usar um caractere especial,we have to escape it.

Outra possibilidade é usar a classePattern:

String[] splitByPatternPipe(final String text) {
    return text.split(Pattern.quote("|"));
}

9. Processando todos os caracteres como um fluxo

No caso de processamento detalhado, podemos transformar uma string em umIntStream:

IntStream getStream(final String text) {
    return text.chars();
}

10. Igualdade de referência e igualdade de valor

Embora as strings se pareçam com umprimitive type, they are not.

Portanto, temos que distinguir entre igualdade de referência e igualdade de valor. Igualdade de referência sempre implica igualdade de valor, mas em geral não o contrário. O primeiro, verificamos com a operação ‘== 'e o último, com o métodoequals:

@Test
public void whenUsingEquals_thenWeCheckForTheSameValue() {
    assertTrue("Values are equal", new String("Test").equals("Test"));
}

@Test
public void whenUsingEqualsSign_thenWeCheckForReferenceEquality() {
    assertFalse("References are not equal", new String("Test") == "Test");
}

Observe que os literais sãointerned in the string pool. Portanto, o compilador às vezes pode otimizá-los para a mesma referência:

@Test
public void whenTheCompileCanBuildUpAString_thenWeGetTheSameReference() {
    assertTrue("Literals are concatenated by the compiler", "Test" == "Te"+"st");
}

11. String em branco vs. String vazia

Há uma diferença sutil entreisBlank eisEmpty.

Uma string está vazia se fornull ou tiver comprimento zero. Whereas a string is blank if it’s null or contains only whitespace characters:

@Test
public void whenUsingIsEmpty_thenWeCheckForNullorLengthZero() {
    assertTrue("null is empty", isEmpty(null));
    assertTrue("nothing is empty", isEmpty(""));
    assertFalse("whitespace is not empty", isEmpty(" "));
    assertFalse("whitespace is not empty", isEmpty("\n"));
    assertFalse("whitespace is not empty", isEmpty("\t"));
    assertFalse("text is not empty", isEmpty("Anything!"));
}

@Test
public void whenUsingIsBlank_thenWeCheckForNullorOnlyContainingWhitespace() {
    assertTrue("null is blank", isBlank(null));
    assertTrue("nothing is blank", isBlank(""));
    assertTrue("whitespace is blank", isBlank("\t\t \t\n\r"));
    assertFalse("test is not blank", isBlank("Anything!"));
}

12. Conclusão

Strings são um tipo de núcleo em todos os tipos de aplicativos. Neste tutorial, aprendemos algumas operações importantes em cenários comuns.

Além disso, demos instruções para referências mais detalhadas.

Finalmente, o código completo com todos os exemplos está disponível em nossoGitHub repository.