Character search function

0

I am trying to write a function that returns the index of the character. For example, I want to fetch the 'a' index 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);

It should print 40, but returns the wrong index.

    
asked by anonymous 16.02.2018 / 18:19

1 answer

0

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

The way you are (indenting correctly):

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

It will make if(count==n) run regardless of whether it is in the right letter or not.

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

  • Catch the first a of String at 7
  • Change% from% to% with%
  • Refresh count because 1 equals index
  • The next letter is no longer count but n continues to a , so it refreshes count to 1 wrong. It will continue to update to the next few letters until index increases again or 8 ends.

Solve this easily with count , including the second String on 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 can the {} be updated.

Once found the position is no longer useful to do any other processing. For this reason you can further improve the method by moving the return directly into 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
}

In this way your code not only does not make unnecessary processing, it's even simpler.

Also note how I changed the return value when it does not exist for index , which is a universal value for this type of function. This return exchange made the variable if not even necessary.

See this code working on Ideone

Note that to have the -1 you indicated must be the 4th index and not the 5th because the first is uppercase and therefore does not count.

    
16.02.2018 / 22:30