2013-07-31 43 views
0

我试着写函数在C++来解析URL并从URL中的端口号和协议,并与不同的端口号,协议所取代。解析URL并用C代替协议和端口号++

对于。例如。 原始地址

https://abc.com:8140/abc/bcd 

我需要替换HTTP和端口号的HTTPS作为6143和合并的像

http://abc.com:6143/abc/bcd 

我使用的操作系统为Windows 7和Visulad Studio 6.0中的URL路径。

感谢,

+0

我们会更加倾向于帮助你理清任何问题,如果你告诉我们,你”已经尝试过。 – Borgleader

回答

0

用MFC快速和肮脏的解决方案:

static TCHAR strhttp[] = L"http:" ; 
void Replace(CString & oldurl, CString & newurl, LPTSTR newport) 
{ 
    int colonposition ; 

    colonposition = oldurl.Find(':') ; 

    if (colonposition != -1) 
    { 
    newurl = (CString)strhttp + oldurl.Mid(colonposition + 1) ; 

    colonposition = newurl.Find(':', _tcslen(strhttp) + 1) ; 

    if (colonposition != -1) 
    { 
     int slashposition = newurl.Find('/', colonposition) ; 
     newurl = newurl.Left(colonposition + 1) + newport + newurl.Mid(slashposition) ; 
    } 
    } 
} 

用法:

CString oldurl = L"https://abc.com:8140/abc/bcd";  
CString newurl ; 
Replace(oldurl, newurl, L"6143") ; 
// now newurl contains the transformed URL 
0

一个解决问题的方法是regular expressions

+0

不,最简单的解决方案是循环访问字符数组。正则表达式很丑陋,速度较慢,需要额外的技能,但会导致较小的代码。 –

0

C++ 11或升压提供的正则表达式的支持。 在你的情况2简单表达应足以:

  1. ^HTTPS://以匹配协议,
  2. :\ d {1,5} /以匹配的端口号

刚刚开发和测试使用http://www.regextester.com/

那些正则表达式2现在,如果你看一下下面的代码,我们声明2正则表达式,并使用与C++ STL 11来的regex_replace功能。

#include <string> 
#include <regex> 
#include <iostream> 

int main(int argc, char* argv[]) 
{ 

    std::string input ("https://abc.com:8140/abc/bcd"); 
    std::string output_reference ("http://abc.com:6143/abc/bcd"); 

    std::regex re_protocol ("^https?://"); //https to http 
    std::regex re_port(":\\d{1,5}/"); //port number replacement, NB note that we use \\d. 

    std::string result = std::regex_replace(std::regex_replace (input, re_protocol, "http://"), re_port, ":6143/"); 

    if(output_reference != result) { 
     std::cout << "error." << std::endl; 
     return -1; 
    } 
    std::cout << input << " ==> " << result << std::endl; 
    return 0; 
} 

结果是

https://abc.com:8140/abc/bcd ==> http://abc.com:6143/abc/bcd 

注意,作为新的STL采取加速大量灵感,你可以通过使用boost::regex代替std::regex适应的是C++ 11的代码,以旧的C++ 。

#include "boost/regex.hpp" 

boost::regex re_protocol ("^https?://"); //https to http 
boost::regex re_port(":\\d{1,5}/"); //port number replacement, NB note that we use \\d.  
std::string result = boost::regex_replace(boost::regex_replace (input, re_protocol, "http://"), re_port, ":6143/");