题意
字符串分离
思路
用sscanf实现分离,事实上也可以用string数组老老实实挑出分隔符,逻辑我处理不好,换成sscanf了。
把字符串先以://
分成两部分,对后面分别进行处理。
我之前直接用一句sscanf(s,"%[a-zA-Z]://%[a-z,.,-]:%[0-9]/%[a-z,.,-]",protocol,host,port,path);
到了第三例的时候崩了,同学提醒这样写表示里面的符号必需,所以是会出错的。以后注意。
关于sccanf的介绍
代码
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
using namespace std;
int main(){
int n;
cin>>n;
char s[61]={'\0'};
for(int i=1;i<=n;i++){
cin>>s;
char protocol[60]={'\0'},
host[60]={'\0'},
port[60]={'\0'},
path[60]={'\0'},
temp[60]={'\0'},
temp1[60]={'\0'};
cout<<"URL #"<<i<<endl;
sscanf(s,"%[a-zA-Z]://%s",protocol,temp);
sscanf(temp,"%[^/]/%s",temp1,path);
sscanf(temp1,"%[^:]:%s",host,port);
if(!strcmp(protocol,""))
cout<<"Protocol = <default>"<<endl;
else
cout<<"Protocol = "<<protocol<<endl;
if(!strcmp(host,""))
cout<<"Host = <default>"<<endl;
else
cout<<"Host = "<<host<<endl;
if(!strcmp(port,""))
cout<<"Port = <default>"<<endl;
else
cout<<"Port = "<<port<<endl;
if(!strcmp(path,""))
cout<<"Path = <default>"<<endl;
else
cout<<"Path = "<<path<<endl;
cout<<endl;
}
return 0;
}