Home > database >  Is there a function to split by the FIRST instance of a delimiter in C?
Is there a function to split by the FIRST instance of a delimiter in C?

Time:03-06

I understand that the strtok() function allows you to split a string with a predefined delimiter (or a set of delimiters), but is there a way to split a string by the FIRST INSTANCE of a delimiter?

Example: (Delimiter=":")

Input: "Host: localhost:5000"

Output: ["Host", "localhost:5000"]

The output does not necessarily need to be in a list, but the string needs to be split into two strings.

Thanks for the help!

CodePudding user response:

In C you can easily accomplish this task by using the string class and its members find and substr.

I coded a small snippet to demostrate it:

#include <string>
using namespace std;

void main()
{
    string sInput = "Host:localhost:5000";
    string sSeparator = ":";
    string s1, s2;

    size_t pos = sInput.find(sSeparator);
    s1 = sInput.substr(0, pos);
    s2 = sInput.substr(pos  1, string::npos);

    // Print result strings
    printf(s1.c_str());
    printf("\n");
    printf(s2.c_str());
}

CodePudding user response:

The first time you call strtok, use the delimiter you want to split with.

For the second call, use an empty delimiter string (if you really want the rest of the string) or use "\n", in the case that your string might include a newline character and you don't want that in the split (or even "\r\n"):

    const char* first = strtok(buf, ":");
    const char* rest = strtok(NULL, "");
 /* or:     const char* rest = strtok(NULL, "\n"); */
  • Related