2011-11-02 38 views
1

在C或Objective-C中,我需要一种方法来分离URI和路径,并给出一个完整的URL。如何确定C或Objective-C中的URL,URI和路径?

例子:

给出的URL

mms://a11.l412923342423.c658546.g.lm.akamaistream.net/D/13/414392/v0001/reflector:36751 

获取URL很容易,但我怎么能确定在何处URI结束,所在的路径开始,在C或Objective-C?

我知道URI是a11.l412923342423.c658546.g.lm.akamaistream.net,Path是D/13/414392/v0001/reflector:36751,但是如何以编程方式识别?

我无法弄清楚,任何示例代码将极大地帮助我。谢谢。

+1

我不知道什么是URI,但它通过搜索整个字符串中的第一个“/”来工作吗? –

+1

我想过那个,但是如何识别路径开始的其他斜杠,它不是按顺序排列的? – Winston

+0

你是否对Cocoa编码?如果是这样,请查看'NSURL'。 –

回答

3

貌似//表示URI的起始和随后的/标志着路径的开始:

char *uri_start; // Start of URI 
int uri_length; // Length of URI 
char *path_start; // Start of Path (until end of string) 

uri_start = strstr(url, "//"); 
if (uri_start == NULL) { 
    uri_start = url; 
} else { 
    uri_start += 2; // skip "//" 
} 

path_start = strstr(uri_start, "/"); 

if (path_start == NULL) { 
    path_start = ""; // Path empty 
    uri_length = strlen(uri_start); 
} else { 
    path_start += 1; // skip "/" 
    uri_length = path_start - uri_start - 1; 
} 

编辑: 复制URI:

char uri[300]; // or char *uri = malloc(uri_length + 1); 
memcpy(uri, uri_start, uri_length); // Copy the uri 
uri[uri_length] = '\0'; // nul-terminate the uri string 

或(如果没关系,改变原始字符串):

uri_start[uri_length] = '\0'; // nul-terminates the uri but alters the url 
+0

非常感谢您的代码Klas!我会试试看,并会让你知道结果。 – Winston

+0

嘿Klas,它像一个魅力工作!非常感谢!唯一缺少的东西是我无法正确地获取它,只是单独获取URI(a11.l412923342423.c658546.g.lm.akamaistream.net),没有附加Path。我试图从完整的URL中“减去”路径,但它没有奏效。你能帮我解决一个问题吗? – Winston

+0

不错!我甚至没有通过编译器来运行它。我已经添加了代码来复制uri作为答案的附录。 –

2

可以在URL中查找第三个SLASH,甚至测试第一个和第二个是否连续。

+0

感谢您的快速回答。我不熟悉C或Objective-C。你有没有关于示例代码的建议? – Winston

2

NSURL对象有许多属性,它们给出URL的各种组件。你有没有尝试过使用这些?

+0

我现在是NSURL的文档。谢谢! – Winston