c++ 字符串提取

来源:百度知道 编辑:UC知道 时间:2024/06/29 21:11:59
char *abc;
abc = "127.0.0.1|1024";
怎么用标准C++把127.0.0.1提取出来成字符串
1024提取出来成数字

功能:
给定形如“127.0.0.1|1024”的字符串,提取出IP地址字符串和整型端口号。
其中IP和端口号分隔符“|”可替换,默认为“:”,但不可为“.”。

代码如下(VC6+WinXP调试通过):

#include <iostream>
#include <string>

using namespace std;

void getIP( const string fullIP, string& IP, unsigned int& port, const char dot = ':' )
{
IP = fullIP.substr( 0, fullIP.find_first_of(dot) );
port = atoi( fullIP.substr( fullIP.find_first_of(dot)+1, fullIP.length() ).c_str() );
}

void main()
{
string ip;
unsigned int port = 0;

char abc[] = "127.0.0.1:1024";
getIP( (string)abc, ip, port );
cout << ip << " " << port << endl;

string efg = "192.168.0.1|80";
getIP( efg, ip, port, '|' );
cout << ip << " " << port << endl;
}

atoi可以用IO中的String流实现。因为atoi错误时返回0,0也是有效的输出,没法检查,所以不安全,而用流实现,如果有错误则会抛出异常。