C#修剪字符串,IP地址和端口

C#修剪字符串,IP地址和端口

问题描述:

可能重复:
string split in c#C#修剪字符串,IP地址和端口

你好,大家好我正从插座是看起来像这样连接的IP地址:>>“188.169。 28.103:61635“我怎样才能把IP地址放入一个字符串中,并将端口转换成另一个字符串? 谢谢。

个人而言,我会使用Substring

int colonIndex = text.IndexOf(':'); 
if (colonIndex == -1) 
{ 
    // Or whatever 
    throw new ArgumentException("Invalid host:port format"); 
} 
string host = text.Substring(0, colonIndex); 
string port = text.Substring(colonIndex + 1); 

马克使用string.Split这也太一个很好的选择提到的 - 但是你应该检查零件的数量:

string[] parts = s.Split(':'); 
if (parts.Length != 2) 
{ 
    // Could be just one part, or more than 2... 
    // throw an exception or whatever 
} 
string host = parts[0]; 
string port = parts[1]; 

或者,如果你'对于包含冒号的端口部分感到满意​​(因为我的Substring版本),那么你可以使用:

// Split into at most two parts 
string[] parts = s.Split(new char[] {':'}, 2); 
if (parts.Length != 2) 
{ 
    // This time it means there's no colon at all 
    // throw an exception or whatever 
} 
string host = parts[0]; 
string port = parts[1]; 

另一种选择是使用正则表达式将两部分作为组进行匹配。说实话,我会说现在目前是,但如果事情变得更复杂,它可能会成为一个更具吸引力的选择。 (我倾向于使用简单的字符串操作,直到事情开始越来越多毛多“格局状”,在这一点上,我打破了一些诚惶诚恐正则表达式。)

+0

+1“我打破了有些惶恐的正则表达式” - 瑙你不:)当然,你只是有可能认为他们是丑陋不堪,读? – sehe

+0

我知道这是一个古老的答案,但仍值得一提的是,这与IpV6不兼容,例如端口为1024':: 1:1024'的本地主机地址 – NiKiZe

尝试String.Split

string[] parts = s.Split(':'); 

这将将IP地址设置为parts[0],将端口设置为parts[1]

我会用string.Split()

var parts = ip.Split(':'); 
string ipAddress = parts[0]; 
string port = parts[1]; 

string test = "188.169.28.103:61635"; 

string [] result = test.Split(new char[]{':'}); 

string ip = result[0]; 
string port = result[1];