求公共前缀:编写程序测试一个函数,该函数查找两个单词最长的共同前缀(例如,“global”和“glossary”最长的 共同前缀是“glo”,“department”和“depart”最长的共同前缀是“depart”,“glove”和“dove”最长的共同前缀 是空字符串)。
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string same_prefix(const string& s1, const string& s2)
{
string s;
auto min_size = min(s1.size(), s2.size());
int i = 0;
for (; i != min_size; ++i)
if (s1[i] != s2[i])
break;
s = s1.substr(0, i);
return s;
}
int main()
{
string s1, s2;
cin >> s1 >> s2;
cout << same_prefix(s1, s2) << endl;
system("pause");
}
URL:Internet 上的可用资源可以用简单字符串来表示,被称为“统一资源定位器”(URL,Uniform / Universal Resource Locator)。 URL 的标准格式如下:
协议类型://服务器地址(:端口号)/路径/文件名
在应用中,我们常常需要从一条 URL 中截取远程服务器地址部分(IP 地址或域名),以便进一步处理。 请编写程序,输入为 URL,输出为远程服务器地址部分。例如,下面是 5 组输入和输出数据。
输入数据示例: 输出结果示例:
http://acm.xidian.edu.cn/ acm.xidian.edu.cn
http://qinz.maybe.im/ cn qinz.maybe.im
https://www.something.com:8080/p?id=0 www.something.com
ftp://ftp.anything.com/nothing.zip ftp.anything.com
http://127.0.0.1/a/b/c/d/e 127.0.0.1
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
getline(cin, s);
auto start = s.find("://") + 3;
auto end = s.find_first_of(":/", start);
string s1 = s.substr(start, end - start);
cout << s1 << endl;
system("pause");
}