QUESTION: C string manipulation.

Discussion in 'C' started by wgre0111, Oct 19, 2008.

  1. wgre0111

    wgre0111 New Member

    Joined:
    Oct 19, 2008
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    Greetings,

    I am making an update to a ESQLC program that is using topend to communicate with Windows..

    I have been having a problem separating a string.

    I have column on a table that holds the address of a printer in the following format. 111.111.111.111:4000
    Its not always guaranteed to be that length.

    I pull that list back via FETCh into.... but NOW i want to split it into two different variables. One with the IP and the other with the Port.
    so char oIPnPort[] = "111.123.123.123:5000";
    would be split up and copied into two separate variables

    char oIP[] = "111.1223.123.123";
    char oPort[] = "5000";


    Could someone give me an example of how to do this via C???

    Use of pointers or anything else would be ok... just need help...

    This split would remove the : between the port and IP as well... I know I want to copy whats to the right of the : in one variable"port" and whats to the left of the : in IP.

    THANKS!
     
  2. oogabooga

    oogabooga New Member

    Joined:
    Jan 9, 2008
    Messages:
    115
    Likes Received:
    11
    Trophy Points:
    0
    Low-level:
    Code:
    void split_addr (char *ip_port, char *ip, char *port)
    {
        while (*ip_port && *ip_port != ':')
            *ip++ = *ip_port++;
        *ip = 0;
    
        if (*ip_port++) // if not pointing at null char
            while (*ip_port)
                *port++ = *ip_port++;
        *port = 0;
    }
    Using the library function strtok():
    Code:
    #include <string.h>
    
    void split_addr (char *ip_port, char *ip, char *port)
    {
        char *p;
        p = strtok (ip_port, ":");
        strcpy (ip, p);
        p = strtok (NULL, "");
        if (p) strcpy (port, p);
        else   *port = 0;
    }
    Call either like this:
    Code:
    char oIPnPort[] = "111.123.123.123:5000";
    char oIP[30];
    char oPort[10];
    split_addr (oIPnPort, oIP, oPort);
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice