Ir para o conteúdo principal

Encontre a enésima ocorrência de um caractere no Excel – 3 maneiras rápidas

Encontrar a enésima ocorrência de um caractere específico em uma string de texto no Excel pode ser particularmente útil na análise de dados, onde pode ser necessário analisar strings ou extrair informações com base em determinados delimitadores ou padrões. Por exemplo, vamos encontrar a 2ª ou 3ª ocorrência do caractere “-” em uma string de texto. Demonstrarei técnicas simples para realizar essa tarefa com eficiência.


Encontre a enésima ocorrência de um caractere na string de texto com fórmula

Você pode criar uma fórmula para encontrar a enésima ocorrência de um caractere. Por favor faça o seguinte:

1. Insira ou copie a seguinte fórmula em uma célula onde deseja obter o resultado:

=FIND(CHAR(1),SUBSTITUTE(A2,"-",CHAR(1),2))
Note: Na fórmula acima:
  • A2: a célula que contém a string.
  • -: O personagem que você está procurando.
  • 2: A 2ª ocorrência que você deseja encontrar, você pode alterá-la para 3,4…conforme necessário.

2. Em seguida, arraste o preenchimento da fórmula para baixo para preencher a fórmula em outras células, e a 2ª posição do caractere – são exibidas de uma vez, veja a captura de tela:

Explicação da fórmula:
  • SUBSTITUTO substitui a enésima ocorrência do caractere por um caractere não imprimível (CHAR(1)).
  • ENCONTRAR procura por esse caractere não imprimível, fornecendo a posição da enésima ocorrência.

Encontre a enésima ocorrência de um caractere em uma string de texto com o Kutools para Excel

Se você não gosta de usar fórmulas ou VBA, você pode considerar uma alternativa conveniente – Kutools for Excel. Dentro de seus grupos de Fórmulas, você encontrará um utilitário útil – Descubra onde o caractere aparece enésimo em uma string que identifica e retorna rapidamente a enésima posição de qualquer caractere em uma célula.

Depois de instalar o Kutools para Excel, clique em Kutools > Fórmula Helper > Fórmula Helper para abrir o Fórmula Helper caixa de diálogo. Clique na célula onde deseja colocar o resultado. Então faça o seguinte:

  1. Selecionar Lookup na lista suspensa de Tipo de Fórmula seção;
  2. Escolha Descubra onde o caractere aparece enésimo em uma string in Escolha uma fórmula seção;
  3. Selecione a célula que contém a string que você usa e digite o caractere especificado e a enésima ocorrência nas caixas de texto no Entrada de argumentos seção;
  4. Finalmente, clique em OK botão para obter o resultado.
Tips: Interessado neste recurso, por favor clique para baixar para obter uma avaliação gratuita por 30 dias.

Encontre a enésima ocorrência de um caractere na string de texto com a função definida pelo usuário

Nesta seção, exploraremos como criar e usar uma UDF para encontrar a enésima ocorrência de um caractere no Excel, fornecendo um guia passo a passo para ajudá-lo a otimizar o tratamento de dados.

  1. Mantenha pressionada a ALT + F11 chaves, e abre o Microsoft Visual Basic para Aplicações janela.
  2. Clique inserção > Móduloe cole a macro a seguir na janela do módulo.
     Function FindN(sFindWhat As String, _
    sInputString As String, N As Integer) As Integer
    'Updateby Extendoffice
    Dim J As Integer
    Application.Volatile
    FindN = 0
    For J = 1 To N
    FindN = InStr(FindN + 1, sInputString, sFindWhat)
    If FindN = 0 Then Exit For
    Next
    End Function
  3. Em seguida, feche a janela do vba. Volte para a planilha, insira a seguinte fórmula em uma célula e arraste a alça de preenchimento para baixo para preencher a fórmula em outras células, veja a captura de tela:
    =FindN("-",A2,3)

  4. Artigos relacionados:

    • Conte o número de ocorrências de uma palavra em uma coluna
    • Se você tem uma coluna de dados que inclui alguns valores duplicados conforme a captura de tela mostrada abaixo, agora o que você deseja fazer é contar o número de ocorrências de uma palavra específica nesta coluna. Agora, com este tutorial, apresento alguns truques para resolvê-lo rapidamente no Excel.
    • Extraia um enésimo caractere de uma string
    • Em geral, você pode querer extrair uma string após um caractere específico, mas, neste caso, quero extrair o enésimo caractere de uma string, conforme mostrado na captura de tela abaixo.
    • Extraia os primeiros/últimos n caracteres da string
    • Por exemplo, há uma lista com strings longas em cada célula, e você deseja extrair os primeiros n caracteres de cada string apenas, como os primeiros 3 caracteres de cada string, e agora você pode usar os seguintes métodos para resolvê-lo no Excel .

Melhores ferramentas de produtividade de escritório

🤖 Assistente de IA do Kutools: Revolucionar a análise de dados com base em: Execução Inteligente   |  Gerar Código  |  Crie fórmulas personalizadas  |  Analise dados e gere gráficos  |  Invocar funções do Kutools...
Recursos mais comuns: Encontre, destaque ou identifique duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas  |  Mover colunas  |  Alternar status de visibilidade de colunas ocultas  |  Compare intervalos e colunas ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Palavras, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   ... e mais

Aprimore suas habilidades de Excel com o Kutools para Excel e experimente uma eficiência como nunca antes. Kutools para Excel oferece mais de 300 recursos avançados para aumentar a produtividade e economizar tempo.  Clique aqui para obter o recurso que você mais precisa...

Descrição


Office Tab traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
Comments (28)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Your formula to find the Nth occurrence of a character in a string does not work. Using your example, adding 2 to the results of the imbedded find ensures a starting position for the initial find of a position beyond the 1st two c's but changing the +2 to +3 does not yield the position of the 4th "c", it simply starts the search one character deeper into the string and the result is still the 3rd "c". To find the 4th "c" the search must begin beyond the position of the 3rd "c". I look forward to your new solution.
This comment was minimized by the moderator on the site
Hello, David

Yes, as you said, the first formula does not work correctly, you can apply the second formula:
=FIND(CHAR(1),SUBSTITUTE(A2,"c",CHAR(1),2))

Note: The number "2" in the formula means the second "c", if you want to get the third, fourth "c", just change the number 2 to 3,4 as you need.
Please try, hope it can help you!
This comment was minimized by the moderator on the site
Find formula1 is imperfect. It will be a great help if it is removed. I have lost lot of time trying for 4th occurance of "a" in "vedanarayanan" Thanks.
This comment was minimized by the moderator on the site
To handle the exception of the formula, you can use same with if and iserro
=IF(ISERR(FIND("c",A1,FIND("c",A1)+2)),FIND("c",A1,FIND("c",A1)+0),FIND("c",A1,FIND("c",A1)+2))
This comment was minimized by the moderator on the site
"Substitute" lets you find the Nth occurrence of a term, so combine it with "find" as follows (where 5=5th occurrence):

=FIND(CHAR(1),SUBSTITUTE(A1,"c",CHAR(1),5))
This comment was minimized by the moderator on the site
Excellent! I am glad I scrolled up to review other comments after posting my own.
This comment was minimized by the moderator on the site
This is the correct answer! please replace this whole article with this one line of code.....
This comment was minimized by the moderator on the site
The first formula is completely useless and wrong but it works just correct for this example as the first and second "c"s are adjacent. The correct formula is:


For 2nd occurence -
=FIND("c",A1,FIND("c",A1)+1)

For 3rd occurence -
=FIND("c",A1,FIND("c",A1,FIND("c",A1)+1)+1) and so on...
This comment was minimized by the moderator on the site
Absolutely agree. The +2, or +3 etc.....entirely depends on the spacing between the n and (n+1) occurences of "c". Thus you would have to manually adjust for every cell if you were trying to copy this formula down a column for instance. Essentially the same as manually counting.


Ex. Let's try to find the 4th occurrence of "c" in cell A1 using the provided formula. Per the article we should use +3 in our nested FIND function to find the 4th occurrence.


Text in Cell A1:

"cab car abc cole cube"

Manually counting, the 4th occurrence is the "c" in cole in the character position of 13.


=FIND("c",A1,FIND("c",A1)+3)

The nested function, FIND("c",A1) will find the first occurrence of "c" in position 1.

Therefore,

FIND("c",A1)+3 = 1+3 = 4

Plugging that back into our formula,

=FIND("c",A1,FIND("c",A1)+3) = FIND("c",A1,1+3) = FIND("c",A1,4)

This new formula will look for the first occurrence of "c" beginning from character position 4. The 4th character in the string is the space just after cab.

Therefore, the formula will find the "c" in car and return the value of 5 for our formula. As we know from manually counting we are looking for 13 as the output.
This comment was minimized by the moderator on the site
The firs formula works correct in my version, in the note, it has explained how to find the third or forth or nth "c".

Note: You can change the 2 in the formula based on your needs. For example, if you want to find the fourth position of "c", you can change the 2 to 3. And if you want to find the first position of "c", you shuold change 2 to 0.
This comment was minimized by the moderator on the site
Try to find out the position of the second c with the first sentence of my above comment as the string using the first formula. You'll get to know how correct it is!
This comment was minimized by the moderator on the site
Hello all,

I have a text in an Excel cell " BY TRANSFER-NEFT*HDFC0000001*N08745987123546*J0032331*KUMAR--"

I need a function to extract just "N08745987123546"

Thanks
This comment was minimized by the moderator on the site
Hello, do you want to extract the numbers after No and the number of numbers are fixed? If so, you can use Kutools for Exccel's Extract text function, type No????to extract.
This comment was minimized by the moderator on the site
HI ALL,
I have a text in an Excel cell " BY TRANSFER-NEFT*HDHC0065431*N053112345624801*K0038331*krishna--"
I need a function to extract just "N053112345624801"
This comment was minimized by the moderator on the site
Formula 1 doesn't work on fourth, fifth, sixth etc. so (+3,4,5) will always show third position of letter "c" which is 19 second formula is working though.
This comment was minimized by the moderator on the site
Hello all, I have a text in an Excel cell "23 floyd lane, longville,KN 14564" I need a function to extract just "longville" Thanks
This comment was minimized by the moderator on the site
If you must use a function, try: =TRIM(MID(A1,SEARCH(",",A1)+1,SEARCH("!@#",SUBSTITUTE(A1,",","!@#",2))-SEARCH(",",A1)-1)) Otherwise, you might consider Data > Text to Columns > Delimited (using a comma as the separator).
This comment was minimized by the moderator on the site
Try this: =INDEX(SMALL(IF(MID(A1,MATCH(ROW(INDIRECT(1&":"&LEN(A1))),ROW(INDIRECT(1&":"&LEN(A1))),0),1)="c",MATCH(ROW(INDIRECT(1&":"&LEN(A1))),ROW(INDIRECT(1&":"&LEN(A1))),0),""),MATCH(ROW(INDIRECT(1&":"&LEN(A1)-LEN(SUBSTITUTE(A1,"c","")))),ROW(INDIRECT(1&":"&LEN(A1)-LEN(SUBSTITUTE(A1,"c","")))),0)),2) where "c" is the character required and 2 is the position. Note this is an array formula.
This comment was minimized by the moderator on the site
this is simpler: =INDEX(SMALL(IF(MID(A1,ROW(INDIRECT(1&":"&LEN(A1))),1)="c",ROW(INDIRECT(1&":"&LEN(A1))),""),ROW(INDIRECT(1&":"&LEN(A1)-LEN(SUBSTITUTE(A1,"c",""))))),2)
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations