您好,登錄后才能下訂單哦!
在C語言中,處理和解析URL字符串可以通過一些基本的字符串操作來實現
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
typedef struct {
char *scheme;
char *host;
char *port;
char *path;
char *query;
} URL;
void parse_url(const char *url_str, URL *url) {
const char *ptr = url_str;
const char *end = url_str + strlen(url_str);
// 解析scheme
const char *scheme_end = strstr(ptr, "://");
if (scheme_end == NULL) {
printf("Invalid URL: %s\n", url_str);
return;
}
url->scheme = (char *)malloc(scheme_end - ptr + 1);
memcpy(url->scheme, ptr, scheme_end - ptr);
url->scheme[scheme_end - ptr] = '\0';
ptr = scheme_end + 3;
// 解析host
const char *host_end = strchr(ptr, ':');
if (host_end == NULL || host_end > end) {
host_end = strchr(ptr, '/');
if (host_end == NULL || host_end > end) {
host_end = end;
}
}
url->host = (char *)malloc(host_end - ptr + 1);
memcpy(url->host, ptr, host_end - ptr);
url->host[host_end - ptr] = '\0';
ptr = host_end;
// 解析port
if (*ptr == ':') {
const char *port_end = strchr(ptr + 1, '/');
if (port_end == NULL || port_end > end) {
port_end = end;
}
url->port = (char *)malloc(port_end - ptr);
memcpy(url->port, ptr + 1, port_end - ptr - 1);
url->port[port_end - ptr - 1] = '\0';
ptr = port_end;
} else {
url->port = NULL;
}
// 解析path
if (*ptr == '/') {
const char *path_end = strchr(ptr, '?');
if (path_end == NULL || path_end > end) {
path_end = end;
}
url->path = (char *)malloc(path_end - ptr + 1);
memcpy(url->path, ptr, path_end - ptr);
url->path[path_end - ptr] = '\0';
ptr = path_end;
} else {
url->path = NULL;
}
// 解析query
if (*ptr == '?') {
url->query = (char *)malloc(end - ptr + 1);
memcpy(url->query, ptr, end - ptr);
url->query[end - ptr] = '\0';
} else {
url->query = NULL;
}
}
void reconstruct_url(const URL *url, char **url_str) {
int len = strlen(url->scheme) + strlen(url->host) + 3; // "://"
if (url->port != NULL) {
len += strlen(url->port) + 1; // ":"
}
if (url->path != NULL) {
len += strlen(url->path);
}
if (url->query != NULL) {
len += strlen(url->query) + 1; // "?"
}
*url_str = (char *)malloc(len + 1);
sprintf(*url_str, "%s://%s", url->scheme, url->host);
if (url->port != NULL) {
strcat(*url_str, ":");
strcat(*url_str, url->port);
}
if (url->path != NULL) {
strcat(*url_str, url->path);
}
if (url->query != NULL) {
strcat(*url_str, "?");
strcat(*url_str, url->query);
}
}
int main() {
const char *url_str = "https://www.example.com:80/path?query";
URL url;
parse_url(url_str, &url);
char *reconstructed_url_str;
reconstruct_url(&url, &reconstructed_url_str);
printf("Original URL: %s\n", url_str);
printf("Reconstructed URL: %s\n", reconstructed_url_str);
free(url.scheme);
free(url.host);
free(url.port);
free(url.path);
free(url.query);
free(reconstructed_url_str);
return 0;
}
這個示例中的parse_url
函數將輸入的URL字符串解析為一個URL結構體。reconstruct_url
函數則根據URL結構體重新構建URL字符串。注意,這個示例僅適用于簡單的URL,對于包含特殊字符或編碼的URL可能需要進一步處理。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。