How do I search a value within a String?

Asked

Viewed 2,193 times

-5

I created a EditText for the user to enter a value, and as soon as they click the search button on String the value entered by him, but I would like to know how to search some value within the String!

  • You only want to know if there is value within the string? How is your code?

  • Well, I have an Edittext that will be used to collect the keyword, and I have a string like this: String[][] table = {"Cristiano","32","Italia"}};

  • Didn’t you already ask this question? http://answall.com/questions/49276/como-crea-um-filtro-de-search-para-uma-string-3D

  • No, this question refers to creating a filter to display results, I’m just asking how to search for some value in a String!

  • But you put a array of string, like you had asked in the other question.

  • Just help me with my question please, just look for a value within a String!

  • 1

    Please edit your question! Do it right.

  • @Victor already helped me, can close the post!

Show 3 more comments

4 answers

7


First of all, you don’t seem to know exactly what a String. That’s a String:

String

THAT’S NOT A String:

String[]

THAT IS NOT A String:

String[][]

Okay, so what’s a String[] and a String[][]?

A String[] is a array of Strings. That is, a sequence of Strings. The [] denotes that it is a array.

In this way int[] is a array whole, Thread[] is a array of Threads and Batata[] is a array potato.

And then what is String[][]? The answer is that this is a array of arrays of Strings!

A way to declare a array that’s how it is:

String[] meuArray = {"Pedro", "Carlos", "Maria"};

This declares an array with three positions, containing the Strings "Pedro", "Carlos" and "Maria", respectively. To access the array, you use the following syntax:

String elemento = meuArray[0]; // O resultado é "Pedro".

Remember that the first element of array is at zero position. This means that the latter will be at zero position meuArray.length - 1. You use the meuArray.length to get the size of the array. That is, the last index corresponds to the size of the array minus one.

Matrices (indexed by two indices, typically row and column) are often represented in java as arrays of arrays. In this way, it is possible to use the first index to index the row and the second the column. The reason is that since the matrix is a array of array of Strings, by indexing an element of it, the result is a array of Strings. When indexing a second time, the result is String.

Thus, you can declare a matrix of Strings like this:

String[][] table = {{"Cristiano", "32", "Italia"}, {"Marcos", "45", "Canada"}};

When indexing an element, the result is a array of Strings:

String[] linha = table[1]; // O resultado é {"Marcos", "45", "Canada"}.

When indexing twice, the result is one String:

String lugar = table[1][2]; // O resultado é "Canada".

Therefore, it is useful to say that a String[][] is a two-dimensional matrix of Strings, because we have two dimensions. Although actually this is a array of arrays of Strings.

Likewise, a String[][][] is a three-dimensional matrix of Strings, because we have three dimensions (and therefore we have to index three times to reach the Strings). Actually this is just one array of arrays of arrays of Strings.

So, how to know if a certain String is within a matrix of Strings? Like this:

String[][] table = {{"Cristiano","32","Italia"},{"Marcos","45","Canada"}};
String oQueQueroPesquisar = "Cristiano";
boolean achou = false;

// Percorre o primeiro índice de 0 até o tamanho do array - 1.
externo: for (int i = 0; i < table.length; i++) {

    // Percorre o segundo índice de 0 até o tamanho do array - 1.
    for (int j = 0; j < table[i].length; j++) {

        // Se é o que queria encontrar, marca que achou.
        if (oQueQueroPesquisar.equals(table[i][j])) {
            achou = true;
            break externo; // Sai do laço. Não apenas do interno, do externo também.
        }
    }
}

if (achou) {
    System.out.println("Achei");
} else {
    System.out.println("Não achei");
}

The method equals is used to check if two objects are equal. In this case, it is used to check if the String of the matrix and the String searching are the same.

And how to know where it was found? Just modify a little the code above:

String[][] table = {{"Cristiano","32","Italia"},{"Marcos","45","Canada"}};
String oQueQueroPesquisar = "Cristiano";
boolean achou = false;
int acheiI = -1, acheiJ = -1;

// Percorre o primeiro índice de 0 até o tamanho do array - 1.
externo: for (int i = 0; i < table.length; i++) {

    // Percorre o segundo índice de 0 até o tamanho do array - 1.
    for (int j = 0; j < table[i].length; j++) {

        // Se é o que queria encontrar, marca que achou e também aonde achou.
        if (oQueQueroPesquisar.equals(table[i][j])) {
            achou = true;
            acheiI = i;
            acheiJ = j;
            break; // Sai do laço. Não apenas do interno, do externo também.
        }
    }
}

if (achou) {
    System.out.println("Achei na linha " + acheiI + " e coluna " + acheiJ);
} else {
    System.out.println("Não achei");
}

To find out whether a String can be found inside another, we can use the method contains class String. For example:

String a = "Cristiano";
System.out.println(a.contains("Cris")); // Imprime true
System.out.println(a.contains("Bob")); // Imprime false

And we can then use this to do partial rather than exact searches. For example to search for "Cris" and find "Cristiano", just exchange this:

if (oQueQueroPesquisar.equals(table[i][j])) {

For this reason:

if (table[i][j].contains(oQueQueroPesquisar)) {

And then the final code goes like this:

String[][] table = {{"Cristiano","32","Italia"},{"Marcos","45","Canada"}};
String oQueQueroPesquisar = "Cris";
boolean achou = false;
int acheiI = -1, acheiJ = -1;

// Percorre o primeiro índice de 0 até o tamanho do array - 1.
externo: for (int i = 0; i < table.length; i++) {

    // Percorre o segundo índice de 0 até o tamanho do array - 1.
    for (int j = 0; j < table[i].length; j++) {

        // Se é o que queria encontrar, marca que achou e também aonde achou.
        if (table[i][j].contains(oQueQueroPesquisar)) {
            achou = true;
            acheiI = i;
            acheiJ = j;
            break externo; // Sai do laço. Não apenas do interno, do externo também.
        }
    }
}

if (achou) {
    System.out.println("Achei " + table[acheiI][acheiJ] + " na linha " + acheiI + " e coluna " + acheiJ);
} else {
    System.out.println("Não achei");
}

Note that inside the if (achou) { I use the table[acheiI][acheiJ] to show the String complete that has been found.


Ah yes, finally array and ArrayList are very different things. Do not confuse them, ok?

And also "String multi-values" does not exist. What exists is array of Strings.


In C, C++, C#, Java, Javascript and similar languages, the loop for has four parts: A boot instruction, an input condition, an increment instruction and a body. Its structure is as follows::

for (<instrução de inicialização>; <condição de entrada>; <instrução de incremento>) {
    <corpo>
}

The loop is executed as follows:

  1. The initialization instruction is executed.
  2. The input condition is evaluated. If false, nothing else will execute on the loop.
  3. If the input condition is true, the body is executed.
  4. Increment statement is executed.
  5. Go to step 2 and continue as many times as necessary.

You may have noticed that this way of performing is not very different from the loop while. In fact, the bow for is nothing more than a while embellished. For example, this tie for:

for (int i = 0; i < array.length; i++) {
    // Corpo
}

It’s almost equivalent to this while:

{
    int i = 0;
    while (i < array.length) {
        // Corpo
        i++;
    }
}

The only difference that makes it "almost equivalent" rather than "perfectly equivalent" is that the execution of an instruction continue within the for has to execute the increment instruction, which does not occur in the while. In the case of break, the behavior is also identical. Taking this small detail from the continue, the tie for above is equivalent to while.

Furthermore, although it is unusual, the for need not necessarily use indexes. For example:

for (Elemento e = lista.getPrimeiroElemento(); e != null; e = e.procurarProximoElemento()) {
    // Corpo.
}

In java, starting from version 5, there is a second valid form for the loop for:

for (<Declaração de variável> : <conjunto de elementos>) {
    <corpo>
}

This form is officially called Enhanced-for, which can be translated into Portuguese as be enhanced. There are also those who call her for-each and is especially useful for browsing arrays. The set of elements shall be a array or something that implements the interface Iterable java. Let’s leave the Iterable from the side (this is already a more advanced topic) and focus only on arrays. For example:

String[] meuArray = {"Pedro", "Carlos", "Maria"};
for (String nome : meuArray) {
    System.out.println(nome);
}

In this loop, in the first iteration the variable nome will be "Pedro". In the second iteration it will be "Carlos" and in the third will be "Maria".

The advantage of this kind of bond is that it leaves the for simpler. The idea is that you should not have to worry about the indexes used to access the array if the compiler can do this for you. In this case for above, it would be equivalent to this for traditional:

String[] meuArray = {"Pedro", "Carlos", "Maria"};
for (int i = 0; i < meuArray.length; i++) {
    String nome = meuArray[i];
    System.out.println(nome);
}

Use the enchanced-for where possible leaves your code simpler and leaner, because you no longer need to worry about the indexes used to access the arrays. On the other hand, the Enhanced-for is more limited than the for and cannot be applied in all cases, in particular it is not possible to replace the for traditional by Enhanced-for in the following cases:

  • If you need to use the index to do something other than simply access the element being iterated on array.
  • If you need to be going through the elements of array in an order that is not just from first to last, one-by-one, one at a time. For example, if you’re going back-to-front, or just the second half, or just the elements in even positions, or anything like that, you can’t use the Enhanced-for.
  • If you are using the for for a purpose other than to arrays or Iterables.

But at least half the time, what you want is exactly to go through the elements of a array (or Iterable) one-by-one, from first to last, one at a time and would use the index just to do that and nothing else, and in these cases it is best to use the Enhanced-for to not have to worry about the indexes.


Back to your code, and if there are multiple values in the result you want?

Well, first let’s organize the code a little better, and define a class to represent the result of the search:

public class ResultadoPesquisa {
    private final int linha;
    private final int coluna;
    private final String palavra;
    private final String encontrada;

    public ResultadoPesquisa(String procurada, String encontrada, int linha, int coluna) {
        this.procurada = procurada;
        this.encontrada = encontrada;
        this.linha = linha;
        this.coluna = coluna;
    }

    public String getProcurada() {
        return procurada;
    }

    public String getEncontrada() {
        return encontrada;
    }

    public int getLinha() {
        return linha;
    }

    public int getColuna() {
        return coluna;
    }

    @Override
    public toString() {
        return "Procurei " + procurada + " e encontrei " + encontrada + " na linha " + linha + " e coluna " + coluna;
    }
}

That is, each search result consists of a set of data containing the word you searched for, the word you found and the row and columns where the word was found.

Let’s first modify your code to use this new class:

String[][] table = {{"Cristiano","32","Italia"},{"Marcos","45","Canada"}};
String oQueQueroPesquisar = "Cris";
ResultadoPesquisa resultado = null;

// Percorre o primeiro índice de 0 até o tamanho do array - 1.
externo: for (int i = 0; i < table.length; i++) {

    // Percorre o segundo índice de 0 até o tamanho do array - 1.
    for (int j = 0; j < table[i].length; j++) {

        // Se é o que queria encontrar, marca que achou e também aonde achou.
        if (table[i][j].contains(oQueQueroPesquisar)) {
            resultado = new ResultadoPesquisa(oQueQueroPesquisar, table[i][j], i, j);
            break externo; // Sai do laço. Não apenas do interno, do externo também.
        }
    }
}

if (resultado != null) {
    System.out.println(resultado);
} else {
    System.out.println("Não achei");
}

How could we then have multiple results? We could put them into one array. Although this approach is possible and valid, it brings certain complexity to have to control the size of the array. This is problematic because we don’t know if in advance how many results we will find, and the array should be created already knowing its size.

The ideal would be to have something similar to a array that automatically increased in size. Well, this is where we found the interface List. As the name suggests, List represents a list of elements. However, this interface has specialized methods to insert elements at the end (without knowing which position is the end), methods to replace elements, methods to exclude elements (and exclude elements in arrays is complicated, since taking an element from the middle of a array will leave a hole and it would be necessary to move the later elements). Anyway, it is much more flexible than a array.

List is an interface. We cannot instantiate interfaces, only implementations. We have several implementations of this interface within JDK for various purposes, but two implementations are particularly important: ArrayList and LinkedList. The class ArrayList is a class that uses a array under the table and she cares to do the hard work with the array (control its size, increase or decrease the array when necessary, move items when there is removal). Now LinkedList is a class that is based on a sequence of nodes where each node meets the next and the previous. In most cases you will want to use the ArrayList, which occupies less memory and allows you to access the elements in an arbitrary order very quickly (unlike LinkedList, where you have to travel them from the beginning). But there are in some scenarios, mainly where the performance would be degraded by multiple displacements due to exclusions, you might want to use LinkedList instead.

So let’s put the found results in a list:

String[][] table = {{"Cristiano","32","Italia"},{"Marcos","45","Canada"}};
String oQueQueroPesquisar = "Cris";
List<ResultadoPesquisa> resultados = new ArrayList<>();

// Percorre o primeiro índice de 0 até o tamanho do array - 1.
for (int i = 0; i < table.length; i++) {

    // Percorre o segundo índice de 0 até o tamanho do array - 1.
    for (int j = 0; j < table[i].length; j++) {

        // Se é o que queria encontrar, marca que achou e também aonde achou.
        if (table[i][j].contains(oQueQueroPesquisar)) {
            resultados.add(new ResultadoPesquisa(oQueQueroPesquisar, table[i][j], i, j));
            // Não sai de nenhum dos laços. Apenas continua neles para encontrar mais resultados.
        }
    }
}

if (!resultados.isEmpty()) {
    System.out.println(resultados);
} else {
    System.out.println("Não achei");
}

At some point, you’ll probably want to scroll through the list. How to do this? Remember the Iterable back there? Yeah, the interface List has a superinterface Collection (representing sets of elements, not necessarily ordered as in List), which in turn has a superinterface which is the Iterable. A Iterable corresponds to an object that provides a sequence of elements to be traversed.

Therefore, a list can be traversed using the Enhanced-for:

for (ResultadoPesquisa r : resultados) {
    System.out.println(r);
}

Almost always, when you want to go through the list elements, the Enhanced-for will be enough. If not, then you can use the Iterator.

Basically, the compiler will transform the Enhanced-for traversing a Iterable in a while, which is what you’ll probably use if you have to do something with the list that you can’t do with the enchanced-for. In this case you will get an object Iterator which will give you the items sequentially. This for above is equivalent to this while:

Iterator<ResultadoPesquisa> it = resultados.iterator();
while (it.hasNext()) {
    ResultadoPesquisa r = it.next();
    System.out.println(r);
}

The method iterator (defined at the interface Iterable) creates the Iterator. The method hasNext of Iterator says if there is any other element to be covered. The method next does two things: provides the element to be covered and moves the Iterator to the next element.

The Iterator also has the method remove which allows you to remove the element that is being iterated, if you need to:

Iterator<ResultadoPesquisa> it = resultados.iterator();
while (it.hasNext()) {
    ResultadoPesquisa r = it.next();
    if (<não quero este resultado>) it.remove(); // O resultado r é retirado da lista.
}

Heed: Call the method next after iteration has finished will cause an exception NoSuchElementException, never call him under any circumstances where the hasNext() would return false.

Attention 2: Some types of lists and other things they implement Iterable correspond to things that cannot be modified. When this is the case, the method remove will make an exception UnsupportedOperationException.

Attention 3: Try to modify the list you are iterating, other than by using the method remove of Iterator may cause a type exception ConcurrentModificationException be launched. So unless you are sure that the type of list in question is designed to allow modifications at the same time as modifications occur, you should not try to do this.

  • 1

    Killed the two questions he asked with a single answer.

  • I just think the bigger example should be contains and at the end you can talk about equals, to give greater visibility to the solution.

  • @Rafaelbluhm I agree, but at the time of writing the text I could not come up with something introduce the two concepts one at a time in a way that would be simple for those who are at an absolutely beginner level. I even tried first to explain the contains and then come with the fors, but I think it’s a bit confusing to come up with a code that does partial searches and then comes up with an easier one to do exact searches. However, at the end of the answer I put the complete code.

  • Victor, could you explain in detail how a "for"?

  • @Jeiferson Feito.

  • @Victor vlw dude...

  • @Victor, I have only one question left, and if in the array there is more than one value corresponding to the "oQueQueroPdodge" as do to print the two values?

  • @Jeiferson Pronto

  • Victor, know the table[i][j], it is returning only with the first value, the name of the person, how do I access the second value, the third and so on?

  • @Jeiferson did not understand what you meant exactly. Using the List, the class I gave him and the Enhanced-for, you should already have enough for you to access all the values without problems. However, I suggest you ask a new question with the code you now have explaining your question.

  • Okay, I’ll do that... It’s just that it’s printing an array value, I can’t find the rest of the values, and I think the problem is on this line: result = new resultResearch(It’s asking for 5 args, and I don’t know how to get the rest of the values, so I left table[i][j], theQueQueroSwis, theQueQuer, theQueWant to search, and consequently this printing my result and 4 of what I researched) Got it? If you do not intend I create another question with the status of my code...

  • @Jeiferson The constructor of the Result class has 4 args and not 5. Also, if you don’t pass the arguments in the exact way I demonstrated, it won’t work.

  • But I built it with 5, because I wanted to pursue 5 values, or isn’t that how it works? I didn’t do exactly the same as you, so he’s asking for 5 args, tendeu?

  • @Jeiferson NO. That’s not how it works. Each result represents one and only one value. If you want to pursue multiple values, then you will end up with a three-loop structure for one within the other. Two of them traversing the matrix and a third traversing the values you seek.

  • So for me to get the second table value I need to do one more table value? example, if I want to print the person’s age, how do I do?

  • @Jeiferson Ask another question because I can no longer know how your code is at the moment, as it must be quite different from what it was originally. What you are needing now must also be quite different from what you need before, so I think you better create another question.

  • Okay, I’ll do it... VLW!

Show 12 more comments

1

If the question really is only about what is written, Java has a function ready for it.

String s1 = "isto é apenas um teste";
String s2 = "teste";
System.out.println(s1.contains(s2));

Documentation.

  • But my String holds multi-values, like: String[][] table = {"Cristiano","32","Italia"},{"Marcos","45","Canada"}};

  • It is i that I am speaking, you do not detail your question, it is difficult to answer. There’s no way to know exactly what you want if you don’t write clearly. What you’re putting there, for me, is the same as the other question.

  • Dexa Keto guy...

  • @For the record, that’s not a String.

  • String that holds multi-values? Cara, da uma lida, is just a multidimensional array of strings, not a string.

  • I’m sorry then... But could someone help me how to search a value in a "multidimensional array"?

  • People may help you but you have already asked this question http://answall.com/questions/49276/como-creat-um-filtro-de-research_para-uma-string-tridimensional. That’s where you should focus with the search question on array multidimensional. Maybe you haven’t gotten an answer yet because people haven’t understood what you want. Then you should edit the question and provide more detail or make your need clearer. You need help, you must help people help you.

Show 2 more comments

1

This is a two-dimensional array/vector string, where it can be accessed like this:

table[ROW][COLUMN]

table.length    , retorna o tamanho da linha.
table[0].length , retorna o tamanho da coluna.

Now see if this example helps:

String busca = "Canada";
System.out.println("Busca: "  + busca + "\n");

String[][] table = {{"Cristiano","32","Italia"},
        {"Marcos","45","Canada"}};

for(int i=0;i < table.length;i++){ // Percorre as linhas
    for(int j=0;j < table[i].length;j++){ // Percorre as colunas

        // Verifica se a busca é igual ao texto em questão
        if(busca.equals(table[i][j]) == true){
            System.out.println("Nome: "  + table[i][0]);
            System.out.println("Idade: " + table[i][1]);
            System.out.println("País: "  + table[i][2]);
        }

    }
}
  • Would not be table[i].length?

  • yes, corrected :)

  • Josinaldo, I take a look at your code and I realized that the String search due what it will look for, then I modified it to receive the value that the user type in Edittext, but this giving error, it was to look like this: String search = etSearch; he points out that he is not able to convert!

  • this is an example, you have to "adapt it" to what you need, from what I understand you’re picking for an Edittext, so it would be (if I haven’t forgotten) nameEditText.gettext(takes the value of the string).

  • Yes, it is named DoEditText.gettext(). toString();

  • o. O, sure it’s not just . gettext(); ?

Show 1 more comment

0

That’s what you want to do ?

public class MinhaClasse {

    public static void main(String[] args){

        String[][] table = {{"Cristiano","32","Italia"}, {"Marcos","45","Canada"}};

        String minhaString = "Mar";

        for(int j = 0; j < 3; j++)
            for(int i = 0; i < 2; i++)
                if( table[i][j].contains(minhaString) )
                    System.out.println(table[i][j]);
     }
}

Printing:

Marcos
  • exact, obg dude, is that I’m still having a hard time using the for, I still don’t understand the logic of it... but thank you very much!

  • 'Cause mark the question as answered, and next time try to be more specific.

Browser other questions tagged

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