How to compare only part of a Java String

Asked

Viewed 1,120 times

-2

String str = new String("Bruno Oliveira");
String str2 = new String("Gustavo Oliveira");

System.out.println(str.equals(str2)); //retorna false

How to compare only certain part of a string?

  • Explain better what you want. What part? In programming things need to be well defined.

  • I want to compare Oliveira.

  • I’d like to give a message.

  • You want to treat only the part after space?

  • 5

    @Jéfersonbueno he died :D

2 answers

2

I believe you wanted something like:

    String str = new String("Bruno Oliveira");
    String str2 = new String("Gustavo Oliveira");

    //cria array de strings usando o espaço como separador
    String[] arr = str2.split(" ");

    // busca na string alvo cada pedaço da string separada
    for (String s : arr) { 
        if (str.contains(s)) {
            System.out.println("match: " + s);
        }
    }
//retorno
//match: Oliveira

0

I don’t know what you really need, but I understand you want to locate a substring within a string and compare whether the substring is contained in another string, if this is really the case, you can use the contains (of the first string in association with the method substring of the second string. In the example below, I passed the initial indexes of substring. This may not be the best approach, because not all texts have a fixed size, but it’s just for example.

    String s = new String("Bruno Oliveira");
    String s1 = new String("Gustavo Oliveira");
    System.out.println(s.contains(s1.substring(8,16)));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.