Split string by a substring

前端 未结 4 727
清酒与你
清酒与你 2021-01-19 16:48

I have following string:

char str[] = \"A/USING=B)\";

I want to split to get separate A and B values with /

4条回答
  •  不要未来只要你来
    2021-01-19 17:00

    As others have pointed out, you can use strstr from to find the delimiter in your string. Then either copy the substrings or modify the input string to split it.

    Here's an implementation that returns the second part of a split string. If the string can't be split, it returns NULL and the original string is unchanged. If you need to split the string into more substrings, you can call the function on the tail repeatedly. The first part will be the input string, possibly shortened.

    #include 
    #include 
    #include 
    
    char *split(char *str, const char *delim)
    {
        char *p = strstr(str, delim);
    
        if (p == NULL) return NULL;     // delimiter not found
    
        *p = '\0';                      // terminate string after head
        return p + strlen(delim);       // return tail substring
    }
    
    int main(void)
    {
        char str[] = "A/USING=B";
        char *tail;
    
        tail = split(str, "/USING=");
    
        if (tail) {
            printf("head: '%s'\n", str);
            printf("tail: '%s'\n", tail);
        }
    
        return 0;
    }
    

提交回复
热议问题