Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Split a complex string in C

Ok, so what I need to do is split a string. Here is an example string that I need to split:

test_french_fries

and let's say I want to split the string into two parts, the part before and after:

french

thus I would get a return of something like:

match[1]=[test_]
match[2]=[_fries]

I have tried messing around with strtok() but I have had no success with that. It appears that strtok() splits the string at all delims that are given - so if I were to give it a delim of french, it would separate the string for each character matched - which ISN'T what I want.

I would like to have a delim where I can provide it a str or char* such as "french" and the string be split before and after the string provided.

Are there any other methods besides strtok() that I could possibly try to implement in order to achieve my desired outcome?

I really appreciate any and all help that I receive.

-Patrick

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

strtok() can only split using a single symbol as separator (1 character), you can specify multiple separators in the form of a null-terminated string, but they are delt with individualy. To split a string with another string as separator, you will have to write a custom function. The example below works just like strtok(), but uses a null-terminated C string as separator:

#include <stdio.h>

char *strstrtok(char *src, char *sep)
{
    static char *str = NULL;
    if (src) str = src;
    else src = str;

    if (str == NULL)
        return NULL;

    char *next = strstr(str, sep);
    if (next)
    {
        *next = '\0';
        str = next + strlen(sep);
    }
    else
        str = NULL;

    return src;
}

int main(void) {
    char buf[] = "yoursepmamasepissepsosepfatsepsheseptooksepasepspoonseptosepthesepsuperbowl";
    char *token = strstrtok(buf, "sep");
    while (token)
    {
        printf("%s ", token);
        token = strstrtok(NULL, "sep");
    }
    return 0;
}

Notice just like strtok(), this solution is not thread-safe.

See it working on Ideone: http://ideone.com/cjRGgJ

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda