从字符串中分离各项
Q:现在有有一个字符串str=“//192.169.3.3:3306:user:pwd”
怎样用c++实现分离出ip,端口号,用户名,密码,注意端口号可能没有(有默认值),谁有好的办法。谢谢。
A.
(1)
#include <iostream> #include <string>
using namespace std;
int main()
{
const string str = "//192.169.3.3:3306:user:pwd";
string tmp;
size_t pos = 2;
tmp = str.substr(pos, str.find(':'));
cout << tmp;
...
return 0;
}
(2)
#include <iostream> #include <deque>
#include <vector>
using namespace std;
void parse(const char* str)
{
char ip[32], user[32], pwd[32];
int port = 0;
if (sscanf(str, "//%[^:]:%d:%[^:]:%s", ip, &port, user, pwd) != 4)
sscanf(str, "//%[^:]:%[^:]:%s", ip, user, pwd);
printf("//%s:%d:%s:%s\n", ip, port, user, pwd);
}
int main(void)
{
parse("//192.169.3.3:3306:user:pwd");
parse("//192.169.3.3:user:pwd");
return 0;
}
(3)
void parse(string str)
{
string ip(""),user(""),pwd("");
int port(80);
int c = count(str.begin(),str.end(),':');
str = str.substr(2);
replace(str.begin(),str.end(),':',' ');
stringstream is(str);
if(c == 2)
is>>ip>>user>>pwd;
else
if(c == 3)
is>>ip>>port>>user>>pwd;
cout < <ip < <endl;
cout < <port < <endl;
cout < <user < <endl;
cout < <pwd < <endl;
}
用stringstream也可以
(4)
#include <string.h> #include <stdio.h>
int main()
{
char str[] = "//192.169.3.3:3306:user:pwd";
char* p;
p = strtok(str,":");
while(p)
{
printf("%s\n",p);
p = strtok(NULL,":");
}
return 0;
}