Function to search character

Asked

Viewed 24 times

0

I’m trying to write a function that returns the index of the character. For example, I want to fetch the index of 'a' the fifth time it appears in the text.

This is my code:

int buscaChar (String text, char c, int n) {
  int index=0;
  int count=0;
  for (int i=0; i<text.length()-1; i++) {
    if (text.charAt(i)==c)
    count=count+1;  
    if(count==n) 
    index= i;
  }
  return index;
}

Function call:

String textCopy = "A linguagem processing e a mais divertida.";

  test=buscaChar(textCopy, 'a', 1); 

 println(test);

Should print 40, but returns incorrect index.

1 answer

0


The problem is that your first if does not cover the second.

The way it is (indenting correctly):

for (int i=0; i<text.length()-1; i++) {
    if (text.charAt(i)==c)
        count=count+1;  
    if(count==n)
        index= i;
}

Will make the if(count==n) is executed, whether or not it is in the right letter.

Imagining the search for the letter a and n to 1 begins with:

  • Catch the first a of String in position 7
  • Alter count for 1
  • Update the index because count is equal to n
  • The next letter is no longer a but the count continues to 1, then updates the index for 8 wrongly. It will continue to update to the following letters until the count increase again or String finish.

Solve this easily with {}, including the second if in the first:

for (int i = 0; i < text.length() - 1; i++) {
    if (text.charAt(i) == c) { //abre aqui
        count = count + 1;
        if (count == n)
            index = i;
    } //fecha aqui incluindo o outro if
}

So only when the letters are equal is there possibility of updating the index.

Once the position is found it is no longer useful to do any other processing. For this reason can still improve the method by moving the return directly into the if:

int buscaChar(String text, char c, int n) {
    int count = 0;
    for (int i = 0; i < text.length() - 1; i++) {
        if (text.charAt(i) == c) {
            count = count + 1;
            if (count == n)
                return i; //apenas return
        }
    }
    return -1; //retorna -1 quando não existe
}

This way your code not only does not do unnecessary processing, but becomes even simpler.

Also note how I changed the return value when it does not exist to -1, which is a universal value for this type of functions. This change of Returns has caused the variable index wasn’t even necessary.

See this code working on Ideone

Note that to have the 40 which you have indicated must be the 4th a and not the 5th because the first is capitalized and therefore does not count.

  • Thanks! Now it worked!

Browser other questions tagged

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